import {
  BadRequestException,
  ConflictException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Parents } from 'src/entities/parents.entity';
import { RoleType, Users } from 'src/entities/users.entity';
import { CreateParentDto } from '../user/dto/create_parent.dto';
import { UpdateParentsDto } from '../user/dto/update_parent.dto';

@Injectable()
export class ParentsService {
  constructor(
    @InjectRepository(Parents)
    private readonly parentsRepository: Repository<Parents>,
    @InjectRepository(Users)
    private readonly usersRepository: Repository<Users>,
  ) {}

  // Création d’un parent
  async create(dto: CreateParentDto): Promise<Parents> {
    const user = await this.usersRepository.findOneBy({ id: dto.user_id });
    if (!user) throw new NotFoundException('Utilisateur introuvable');
    if (user.role !== RoleType.PARENT) {
      throw new BadRequestException('Accès réservé aux parents');
    }

    const exist = await this.parentsRepository.findOneBy({ user_id: dto.user_id });
    if (exist) throw new ConflictException('Ce parent existe déjà');

    let co_parent: Users | null = null;
    if (dto.co_parent_id) {
      co_parent = await this.usersRepository.findOneBy({ id: dto.co_parent_id });
      if (!co_parent) throw new NotFoundException('Co-parent introuvable');
      if (co_parent.role !== RoleType.PARENT) {
        throw new BadRequestException('Accès réservé aux parents');
      }
    }

    const entity = this.parentsRepository.create({
      user_id: dto.user_id,
      user,
      co_parent: co_parent ?? undefined,
    });

    return this.parentsRepository.save(entity);
  }

  // Liste des parents
  async findAll(): Promise<Parents[]> {
    return this.parentsRepository.find({
      relations: ['user', 'co_parent', 'parentChildren', 'dossiers'],
    });
  }

  // Récupérer un parent par user_id
  async findOne(user_id: string): Promise<Parents> {
    const parent = await this.parentsRepository.findOne({
      where: { user_id },
      relations: ['user', 'co_parent', 'parentChildren', 'dossiers'],
    });
    if (!parent) throw new NotFoundException('Parent introuvable');
    return parent;
  }

  // Mise à jour
  async update(id: string, dto: UpdateParentsDto): Promise<Parents> {
    await this.parentsRepository.update(id, dto);
    return this.findOne(id);
  }
}
