import {
  BadRequestException,
  ConflictException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RoleType, Users } from 'src/entities/users.entity';
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';

@Injectable()
export class AssistantesMaternellesService {
  constructor(
    @InjectRepository(AssistanteMaternelle)
    private readonly assistantesMaternelleRepository: Repository<AssistanteMaternelle>,
    @InjectRepository(Users)
    private readonly usersRepository: Repository<Users>
  ) {}

  // Création d’une assistante maternelle
  async create(dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
    const user = await this.usersRepository.findOneBy({ id: dto.user_id });
    if (!user) throw new NotFoundException('Utilisateur introuvable');
    if (user.role !== RoleType.ASSISTANTE_MATERNELLE) {
      throw new BadRequestException('Accès réservé aux assistantes maternelles');
    }

    const exist = await this.assistantesMaternelleRepository.findOneBy({ user_id: dto.user_id });
    if (exist) throw new ConflictException('Assistante maternelle déjà existante');

    const entity = this.assistantesMaternelleRepository.create({
      user_id: dto.user_id,
      user: { ...user, role: RoleType.ASSISTANTE_MATERNELLE },
      approval_number: dto.approval_number,
      nir: dto.nir,
      max_children: dto.max_children,
      biography: dto.biography,
      available: dto.available ?? true,
      residence_city: dto.residence_city,
      agreement_date: dto.agreement_date ? new Date(dto.agreement_date) : undefined,
      years_experience: dto.years_experience,
      specialty: dto.specialty,
      places_available: dto.places_available,
    });

    return this.assistantesMaternelleRepository.save(entity);
  }

  // Liste des assistantes maternelles
  async findAll(): Promise<AssistanteMaternelle[]> {
    return this.assistantesMaternelleRepository.find({
      relations: ['user'],
    });
  }

  // Récupérer une assistante maternelle par user_id
  async findOne(user_id: string): Promise<AssistanteMaternelle> {
    const assistante = await this.assistantesMaternelleRepository.findOne({
      where: { user_id },
      relations: ['user'],
    });
    if (!assistante) throw new NotFoundException('Assistante maternelle introuvable');
    return assistante;
  }

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

  // Suppression d’une assistante maternelle
  async remove(id: string): Promise<{ message: string }> {
    await this.assistantesMaternelleRepository.delete(id);
    return { message: 'Assistante maternelle supprimée' };
  }
}
