-- =====================================================
-- FUNCTION: education.generate_certificate_number()
-- =====================================================
-- Proyecto: OrbiQuant IA (Trading Platform)
-- Módulo: OQI-002 - Education
-- Especificación: ET-EDU-001-database.md
-- Descripción: Genera automáticamente el número de certificado y código de verificación
-- =====================================================

CREATE OR REPLACE FUNCTION education.generate_certificate_number()
RETURNS TRIGGER AS $$
DECLARE
  v_year INTEGER;
  v_sequence INTEGER;
BEGIN
  v_year := EXTRACT(YEAR FROM NOW());

  -- Obtener siguiente número de secuencia para el año
  SELECT COALESCE(MAX(
    CAST(SUBSTRING(certificate_number FROM 14) AS INTEGER)
  ), 0) + 1
  INTO v_sequence
  FROM education.certificates
  WHERE certificate_number LIKE 'OQI-CERT-' || v_year || '-%';

  -- Generar número de certificado: OQI-CERT-2025-00001
  NEW.certificate_number := FORMAT('OQI-CERT-%s-%s',
    v_year,
    LPAD(v_sequence::TEXT, 5, '0')
  );

  -- Generar código de verificación único
  NEW.verification_code := UPPER(
    SUBSTRING(MD5(RANDOM()::TEXT || NOW()::TEXT) FROM 1 FOR 16)
  );

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION education.generate_certificate_number() IS 'Genera número de certificado y código de verificación automáticamente';

-- Trigger para generar número de certificado
CREATE TRIGGER generate_certificate_number_trigger
  BEFORE INSERT ON education.certificates
  FOR EACH ROW
  EXECUTE FUNCTION education.generate_certificate_number();
