import mongoose, { Schema, Document } from 'mongoose';
import { ClinicalProtocol } from '../../../domain/entities/ClinicalProtocol';

const ProtocolStepSchema = new Schema({
  tipo: { type: String, enum: ['checklist', 'decision', 'tecnica', 'info'], required: true },
  titulo: { type: String, required: true },
  descripcion: String,
  items: [String],
  urgencia: { type: String, enum: ['critica'] },
  badge: String,
  parametros: [{
    label: String,
    valor: String,
    destacado: Boolean
  }],
  si: String,
  no: String,
  imagen: String,
  video: String
}, { _id: false });

const ProtocolPhaseSchema = new Schema({
  id: Schema.Types.Mixed,
  nombre: { type: String, required: true },
  icono: String,
  pregunta: String,
  ramas: [{
    condicion: String,
    destino: Schema.Types.Mixed
  }],
  // Reutilizamos campos de step por consistencia
  tipo: String,
  descripcion: String,
  items: [String],
  urgencia: String,
  badge: String,
  parametros: [{ label: String, valor: String, destacado: Boolean }],
  imagen: String,
  video: String
}, { _id: false });

const DrugSchema = new Schema({
  nombre: { type: String, required: true },
  filas: [{ label: String, valor: String }],
  formula: String
}, { _id: false });

const ClinicalProtocolSchema = new Schema({
  id: { type: String, required: true, unique: true },
  titulo: { type: String, required: true },
  subtitulo: String,
  categoria: { type: String, required: true },
  urgencia: { type: String, enum: ['critica', 'alta', 'media', 'baja'], required: true },
  version: { type: String, required: true },
  descripcion: String,
  fuente: String,
  actualizado: String,
  alertas: [{
    tipo: { type: String, enum: ['warning', 'danger', 'info'] },
    texto: String
  }],
  grupos_edad: [{
    id: String,
    label: String,
    sublabel: String
  }],
  parametros_por_grupo: Schema.Types.Map,
  pasos: [ProtocolStepSchema],
  fases: [ProtocolPhaseSchema],
  farmacos: [DrugSchema],
  equipamiento: [String]
}, { 
  timestamps: true,
  collection: 'protocols'
});

export interface ProtocolDocument extends Omit<ClinicalProtocol, 'id'>, Document {}

export const ProtocolModel = mongoose.model<ProtocolDocument>('Protocol', ClinicalProtocolSchema);
