import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Parents } from 'src/entities/parents.entity';
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
import { ParentsService } from '../parents/parents.service';
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
import { DossierAmCompletDto, DossierAmUserDto } from './dto/dossier-am-complet.dto';

/**
 * Endpoint unifié GET /dossiers/:numeroDossier – AM ou famille. Ticket #119.
 */
@Injectable()
export class DossiersService {
  constructor(
    @InjectRepository(Parents)
    private readonly parentsRepository: Repository<Parents>,
    @InjectRepository(AssistanteMaternelle)
    private readonly amRepository: Repository<AssistanteMaternelle>,
    private readonly parentsService: ParentsService,
  ) {}

  async getDossierByNumero(numeroDossier: string): Promise<DossierUnifieDto> {
    const num = numeroDossier?.trim();
    if (!num) {
      throw new NotFoundException('Numéro de dossier requis.');
    }

    // 1) Famille : un parent a ce numéro ?
    const parentWithNum = await this.parentsRepository.findOne({
      where: { numero_dossier: num },
      select: ['user_id'],
    });
    if (parentWithNum) {
      const dossier = await this.parentsService.getDossierFamilleByNumero(num);
      return { type: 'family', dossier };
    }

    // 2) AM : une assistante maternelle a ce numéro ?
    const am = await this.amRepository.findOne({
      where: { numero_dossier: num },
      relations: ['user'],
    });
    if (am?.user) {
      const dossier: DossierAmCompletDto = {
        numero_dossier: num,
        user: this.toDossierAmUserDto(am.user),
        numero_agrement: am.approval_number,
        nir: am.nir,
        biographie: am.biography,
        disponible: am.available,
        ville_residence: am.residence_city,
        date_agrement: am.agreement_date,
        annees_experience: am.years_experience,
        specialite: am.specialty,
        nb_max_enfants: am.max_children,
        place_disponible: am.places_available,
      };
      return { type: 'am', dossier };
    }

    throw new NotFoundException('Aucun dossier trouvé pour ce numéro.');
  }

  private toDossierAmUserDto(user: {
    id: string;
    email: string;
    prenom?: string;
    nom?: string;
    telephone?: string;
    adresse?: string;
    ville?: string;
    code_postal?: string;
    profession?: string;
    date_naissance?: Date;
    lieu_naissance_ville?: string;
    lieu_naissance_pays?: string;
    photo_url?: string;
    consentement_photo?: boolean;
    statut: any;
  }): DossierAmUserDto {
    return {
      id: user.id,
      email: user.email,
      prenom: user.prenom,
      nom: user.nom,
      telephone: user.telephone,
      adresse: user.adresse,
      ville: user.ville,
      code_postal: user.code_postal,
      profession: user.profession,
      date_naissance: user.date_naissance,
      lieu_naissance_ville: user.lieu_naissance_ville,
      lieu_naissance_pays: user.lieu_naissance_pays,
      photo_url: user.photo_url,
      consentement_photo: user.consentement_photo,
      statut: user.statut,
    };
  }
}
