import {
    Injectable,
    NotFoundException,
    HttpException,
    HttpStatus,
    BadRequestException,
    InternalServerErrorException,
    UnauthorizedException
} from '@nestjs/common'
import { Repository, UpdateResult } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { Mask } from './entities/mask.entity'
import { MaskDto } from './dto/mask.dto'
import { HashingService } from '../shared/hashing/hashing.service'
import { SmsService } from '../sms/sms.service'
import { paginate, Pagination } from 'nestjs-typeorm-paginate'
import { PageRequest } from '../common/dto/page-request'

@Injectable()
export class MaskService {
    constructor(
        @InjectRepository(Mask)
        private readonly maskRepository: Repository<Mask>,
        private readonly hashingService: HashingService,
        private readonly smsService: SmsService
    ) {}

    async findAll(req: PageRequest<Mask>): Promise<Pagination<Mask>> {
        return await paginate<Mask>(this.maskRepository, req.page, req.search)
    }
    
    async randomQuery(num: number): Promise<Mask[]> {
        return await this.maskRepository.createQueryBuilder().orderBy("RAND()").limit(num).getMany()
    }

    public async create(maskDto: MaskDto) {
        return await this.maskRepository.save(maskDto)
    }

    public async findById(maskId: number): Promise<Mask> {
        const mask = await this.maskRepository.findOneBy({
            id: +maskId
        })

        if (!mask) {
            throw new NotFoundException(`Mask #${maskId} not found`)
        }

        return mask
    }

    public async updateMask(id: number, maskDto: MaskDto): Promise<UpdateResult> {
        try {
            const mask = await this.maskRepository.update(
                {
                    id: +id
                },
                { ...maskDto }
            )

            return mask
        } catch (err) {
            throw new BadRequestException('Mask not updated')
        }
    }

    public async deleteMask(id: number): Promise<void> {
        const mask = await this.findById(id)
        await this.maskRepository.remove(mask)
    }

}