import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { Repository } from 'typeorm';
import { Permission } from './entities/permission.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Profil } from 'src/gestion-utilisateurs/profils/entities/profil.entity';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    private permissionRepository: Repository<Permission>,

    @InjectRepository(Profil)
    private profilRepository: Repository<Profil>
  ) { }
  async create(createPermissionDto: CreatePermissionDto): Promise<Permission> {
    const existing = await this.permissionRepository.findOneBy({ nom: createPermissionDto.nom });

    if (existing) {
      throw new BadRequestException(`La permission "${createPermissionDto.nom}" existe déjà`);
    }
    return await this.permissionRepository.save(createPermissionDto);
  }

  async findAll(): Promise<Permission[]> {
    return await this.permissionRepository.find();
  }

  async findOne(id: number): Promise<Permission> {
    const permission = await this.permissionRepository.findOneBy({ id })
    if (!permission) {
      throw new NotFoundException('Permission non trouvée')
    }
    return permission
  }

  async update(id: number, updatePermissionDto: UpdatePermissionDto): Promise<Permission> {
    const permission = await this.findOne(id)

    return this.permissionRepository.save({
      ...permission,
      ...updatePermissionDto
    });
  }

  async remove(id: number): Promise<void> {
    this.permissionRepository.delete(id)
  }

  async assignPermission(idPermission: number, idUser: number): Promise<void> {
    const permission = await this.permissionRepository.findOne({ where: { id: idPermission }, relations: ['profils'] })
    const profil = await this.profilRepository.findOneBy({ id: idUser })
    if (!permission) {
      throw new NotFoundException('Permission non trouvée')
    }
    if (!profil) {
      throw new NotFoundException('Profil non trouvé')
    }
    permission?.profils.push(profil)
    await this.permissionRepository.save(permission)
  }

  async removePermission(idPermission: number, idProfil: number): Promise<void> {
    const permission = await this.permissionRepository.findOne({ where: { id: idPermission }, relations: ['profils'] })
    const profil = await this.profilRepository.findOneBy({ id: idProfil })
    if (!permission) {
      throw new NotFoundException('Permission non trouvée')
    }
    if (!profil) {
      throw new NotFoundException('Profil non trouvé')
    }
    permission.profils = permission.profils.filter(p => p.id !== profil.id)
    await this.permissionRepository.save(permission)
  }
}
