import { IProtocolRepository } from '../../domain/repositories/IProtocolRepository';
import { TelephoneProtocol, ProtocolCategory, AgeGroup } from '../../domain/entities/TelephoneProtocol';
import { ClinicalProtocol } from '../../domain/entities/ClinicalProtocol';
import { ProtocolModel } from '../database/models/ProtocolModel';

export class MongoProtocolRepository implements IProtocolRepository {
  async findAll(): Promise<any[]> {
    return await ProtocolModel.find().lean();
  }

  async findById(id: string): Promise<any | null> {
    return await ProtocolModel.findOne({ id }).lean();
  }

  async findByCategory(category: ProtocolCategory): Promise<any[]> {
    return await ProtocolModel.find({ categoria: category }).lean();
  }

  async findByAgeGroup(ageGroup: AgeGroup): Promise<any[]> {
    // Nota: El modelo de ClinicalProtocol maneja grupos_edad de forma distinta
    return await ProtocolModel.find({ 
      $or: [{ 'grupos_edad.id': ageGroup }, { 'grupos_edad': { $exists: false } }] 
    }).lean();
  }

  async save(protocol: any): Promise<void> {
    await ProtocolModel.findOneAndUpdate(
      { id: protocol.id },
      protocol,
      { upsert: true, new: true }
    );
  }

  async delete(id: string): Promise<void> {
    await ProtocolModel.findOneAndDelete({ id });
  }
}
