import {
    Injectable,
    NotFoundException,
    BadRequestException,
} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm';
import { Label } from './entities/label.entity';
import { Repository } from 'typeorm';
import { RoleLabel } from './entities/role-label.entity';
import { LabelDto } from './dto/label.dto';

@Injectable()
export class LabelService {

    constructor(
        @InjectRepository(Label)
        private readonly labelRepository: Repository<Label>,
        @InjectRepository(RoleLabel)
        private readonly roleLabelRepository: Repository<RoleLabel>
    ) { }

    async getRoleLabeltList(id: number): Promise<RoleLabel[]> {
        return await this.roleLabelRepository.createQueryBuilder('roleLabel')
            .where('roleLabel.roleId = :id', { id })
            .getMany();
    }

    async add(labelDto: LabelDto) {
        return await this.labelRepository.save(labelDto)
    }

    async randomQuery(num: number): Promise<Label[]> {
        return await this.labelRepository.createQueryBuilder().orderBy("RAND()").limit(num).getMany()
    }

    async addRoleLabel(roleId: number, labelList: Label[]): Promise<RoleLabel[]> {
        const roleLabelList: RoleLabel[] = []

        labelList.forEach((label) => {
            const roleLabel = new RoleLabel()
            roleLabel.roleId = roleId
            roleLabel.lableId = label.id
            roleLabel.describe = label.describe
            roleLabelList.push(roleLabel)
        })

        return await this.roleLabelRepository.save(roleLabelList)
    }

    async delRoleLabel(list: RoleLabel[]): Promise<void> {
        await this.roleLabelRepository.recover(list)
    }

}