-- Sprint 12: Directorio de fuentes, modos de acceso, recetas iniciales y mapa de cobertura.
-- Compatible con MariaDB 10.4+ y seguro para datos multiempresa.

CREATE TABLE IF NOT EXISTS research_modos_acceso (
  codigo CHAR(5) PRIMARY KEY,
  nombre_es VARCHAR(180) NOT NULL,
  nombre_en VARCHAR(180) NOT NULL,
  tratamiento_es TEXT NOT NULL,
  tratamiento_en TEXT NOT NULL,
  evidencia_minima_es TEXT NOT NULL,
  evidencia_minima_en TEXT NOT NULL,
  automatizacion_permitida ENUM('si','no','parcial','desconocido') NOT NULL DEFAULT 'desconocido',
  requiere_confirmacion_humana TINYINT(1) NOT NULL DEFAULT 1,
  orden TINYINT UNSIGNED NOT NULL,
  activo TINYINT(1) NOT NULL DEFAULT 1,
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_research_modo_orden (orden)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO research_modos_acceso
(codigo,nombre_es,nombre_en,tratamiento_es,tratamiento_en,evidencia_minima_es,evidencia_minima_en,automatizacion_permitida,requiere_confirmacion_humana,orden,activo)
VALUES
('MA-01','Buscador web público','Public web search','Abrir la consulta, registrar parámetros y capturar únicamente resultados permitidos.','Open the search, record parameters and capture only permitted results.','Consulta exacta, filtros, fecha, URL y resultado.','Exact query, filters, date, URL and result.','parcial',1,1,1),
('MA-02','API o descarga oficial','Official API or download','Usar un conector versionado o una importación reproducible sobre datos oficiales.','Use a versioned connector or reproducible import over official data.','Endpoint o archivo, versión, fecha, filtros y hash cuando aplique.','Endpoint or file, version, date, filters and hash when applicable.','si',1,2,1),
('MA-03','PDF, catálogo o inventario estático','Static PDF, catalogue or inventory','Importar o revisar el documento y conservar página, fila, fragmento o signatura.','Import or review the document and preserve page, row, excerpt or reference.','Nombre y versión del archivo, página/fila, fragmento y referencia.','File name and version, page/row, excerpt and reference.','parcial',1,3,1),
('MA-04','Formulario web','Web form','Asistir el llenado cuando esté permitido y exigir confirmación humana antes del envío.','Assist form completion when permitted and require human confirmation before submission.','Formulario utilizado, datos enviados, confirmación, fecha y comprobante.','Form used, submitted data, confirmation, date and receipt.','parcial',1,4,1),
('MA-05','Correo electrónico','Email','Preparar borrador, anexos y seguimiento; el usuario revisa antes de enviar.','Prepare draft, attachments and follow-up; the user reviews before sending.','Destinatario, asunto, cuerpo aprobado, anexos, fecha y respuesta.','Recipient, subject, approved body, attachments, date and reply.','parcial',1,5,1),
('MA-06','Login o suscripción','Login or subscription','El usuario accede con su propia cuenta; GeneaCase registra la consulta sin guardar credenciales.','The user accesses with their own account; GeneaCase records the search without storing credentials.','Portal, fecha, filtros y resultado; nunca contraseña, cookie o token.','Portal, date, filters and result; never password, cookie or token.','no',1,6,1),
('MA-07','CAPTCHA o restricción técnica','CAPTCHA or technical restriction','No automatizar ni evadir. Crear tarea manual y registrar el bloqueo o resultado autorizado.','Do not automate or bypass. Create a manual task and record the block or authorized result.','Control detectado, fecha, captura autorizada y alternativa propuesta.','Detected control, date, authorized capture and proposed alternative.','no',1,7,1),
('MA-08','Consulta física o investigador local','Physical consultation or local researcher','Preparar encargo, alcance, costo, entrega y evidencia mínima para revisión.','Prepare assignment, scope, cost, delivery and minimum evidence for review.','Institución, responsable, instrucciones, costo, fecha y material entregado.','Institution, responsible person, instructions, cost, date and delivered material.','no',1,8,1)
ON DUPLICATE KEY UPDATE
 nombre_es=VALUES(nombre_es),nombre_en=VALUES(nombre_en),tratamiento_es=VALUES(tratamiento_es),tratamiento_en=VALUES(tratamiento_en),
 evidencia_minima_es=VALUES(evidencia_minima_es),evidencia_minima_en=VALUES(evidencia_minima_en),
 automatizacion_permitida=VALUES(automatizacion_permitida),requiere_confirmacion_humana=VALUES(requiere_confirmacion_humana),orden=VALUES(orden),activo=1;

ALTER TABLE research_instituciones
  ADD COLUMN IF NOT EXISTS id_empresa BIGINT UNSIGNED NULL AFTER id;
ALTER TABLE research_instituciones
  ADD COLUMN IF NOT EXISTS tipos_fondo_json JSON NULL AFTER tipo;
ALTER TABLE research_instituciones
  ADD COLUMN IF NOT EXISTS fuente_verificacion_url VARCHAR(1200) NULL AFTER direccion;
ALTER TABLE research_instituciones
  ADD COLUMN IF NOT EXISTS notas_requisitos TEXT NULL AFTER fuente_verificacion_url;
ALTER TABLE research_instituciones
  ADD COLUMN IF NOT EXISTS verificado_por BIGINT UNSIGNED NULL AFTER verificado_en;
ALTER TABLE research_instituciones
  ADD COLUMN IF NOT EXISTS creado_por BIGINT UNSIGNED NULL AFTER activo;

DROP INDEX IF EXISTS uq_institucion_nombre_pais ON research_instituciones;
CREATE UNIQUE INDEX IF NOT EXISTS uq_research_institucion_tenant_nombre_pais
  ON research_instituciones(id_empresa,nombre,pais_codigo);
CREATE INDEX IF NOT EXISTS idx_research_institucion_tenant
  ON research_instituciones(id_empresa,activo,pais_codigo,tipo);

ALTER TABLE research_instituciones
  ADD CONSTRAINT fk_research_institucion_empresa FOREIGN KEY (id_empresa) REFERENCES org_empresas(id) ON DELETE CASCADE,
  ADD CONSTRAINT fk_research_institucion_verificador FOREIGN KEY (verificado_por) REFERENCES org_usuarios(id),
  ADD CONSTRAINT fk_research_institucion_creador FOREIGN KEY (creado_por) REFERENCES org_usuarios(id);

ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS codigo_modo_acceso CHAR(5) NOT NULL DEFAULT 'MA-01' AFTER tipo;
ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS coleccion VARCHAR(300) NULL AFTER nombre;
ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS alcance TEXT NULL AFTER tipos_registro_json;
ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS restricciones TEXT NULL AFTER alcance;
ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS formatos_json JSON NULL AFTER restricciones;
ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS fuente_verificacion_url VARCHAR(1200) NULL AFTER instrucciones;
ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS responsable_verificacion_id BIGINT UNSIGNED NULL AFTER verificado_en;
ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS proxima_revision_en DATE NULL AFTER responsable_verificacion_id;
ALTER TABLE research_fuentes
  ADD COLUMN IF NOT EXISTS version_fuente VARCHAR(120) NULL AFTER proxima_revision_en;

UPDATE research_fuentes
SET codigo_modo_acceso = CASE
  WHEN requiere_captcha=1 THEN 'MA-07'
  WHEN requiere_login=1 OR nivel_acceso IN ('registro','suscripcion') THEN 'MA-06'
  WHEN tipo='api' THEN 'MA-02'
  WHEN tipo IN ('pdf','csv','catalogo') THEN 'MA-03'
  WHEN tipo='formulario' THEN 'MA-04'
  WHEN tipo='correo' THEN 'MA-05'
  WHEN tipo IN ('presencial','investigador_local') OR nivel_acceso='presencial' THEN 'MA-08'
  ELSE 'MA-01'
END;

-- El BOE ya se registró como API oficial aunque su tipo legacy sea portal.
UPDATE research_fuentes SET codigo_modo_acceso='MA-02'
WHERE url='https://www.boe.es/datosabiertos/api/api.php';

CREATE INDEX IF NOT EXISTS idx_research_fuente_tenant_modo_estado
  ON research_fuentes(id_empresa,codigo_modo_acceso,estado);
CREATE INDEX IF NOT EXISTS idx_research_fuente_revision
  ON research_fuentes(proxima_revision_en,estado);

ALTER TABLE research_fuentes
  ADD CONSTRAINT fk_research_fuente_modo FOREIGN KEY (codigo_modo_acceso) REFERENCES research_modos_acceso(codigo),
  ADD CONSTRAINT fk_research_fuente_responsable FOREIGN KEY (responsable_verificacion_id) REFERENCES org_usuarios(id);

CREATE TABLE IF NOT EXISTS research_recetas (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  id_empresa BIGINT UNSIGNED NULL,
  id_fuente BIGINT UNSIGNED NULL,
  codigo_modo_acceso CHAR(5) NOT NULL,
  uuid_publico CHAR(36) NOT NULL UNIQUE,
  nombre VARCHAR(220) NOT NULL,
  nombre_en VARCHAR(220) NULL,
  descripcion TEXT NOT NULL,
  descripcion_en TEXT NULL,
  condicion_cierre TEXT NULL,
  condicion_cierre_en TEXT NULL,
  version VARCHAR(30) NOT NULL DEFAULT '1.0',
  activo TINYINT(1) NOT NULL DEFAULT 1,
  creado_por BIGINT UNSIGNED NULL,
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (id_empresa) REFERENCES org_empresas(id) ON DELETE CASCADE,
  FOREIGN KEY (id_fuente) REFERENCES research_fuentes(id) ON DELETE CASCADE,
  FOREIGN KEY (codigo_modo_acceso) REFERENCES research_modos_acceso(codigo),
  FOREIGN KEY (creado_por) REFERENCES org_usuarios(id),
  INDEX idx_research_receta_tenant_modo (id_empresa,codigo_modo_acceso,activo),
  INDEX idx_research_receta_fuente (id_fuente,activo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS research_receta_pasos (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  id_receta BIGINT UNSIGNED NOT NULL,
  orden INT UNSIGNED NOT NULL DEFAULT 1,
  titulo VARCHAR(220) NOT NULL,
  titulo_en VARCHAR(220) NULL,
  instruccion TEXT NOT NULL,
  instruccion_en TEXT NULL,
  evidencia_esperada TEXT NULL,
  evidencia_esperada_en TEXT NULL,
  advertencia TEXT NULL,
  advertencia_en TEXT NULL,
  requiere_confirmacion_humana TINYINT(1) NOT NULL DEFAULT 1,
  activo TINYINT(1) NOT NULL DEFAULT 1,
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (id_receta) REFERENCES research_recetas(id) ON DELETE CASCADE,
  UNIQUE KEY uq_research_receta_paso_orden (id_receta,orden),
  INDEX idx_research_receta_pasos_activos (id_receta,activo,orden)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS research_fuente_experiencias (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  id_empresa BIGINT UNSIGNED NOT NULL,
  id_fuente BIGINT UNSIGNED NOT NULL,
  fecha_experiencia DATE NOT NULL,
  resultado ENUM('positivo','parcial','negativo','sin_respuesta','rechazado','requiere_pago','requiere_visita','otro') NOT NULL,
  tiempo_respuesta_dias INT UNSIGNED NULL,
  observaciones_privadas TEXT NOT NULL,
  creado_por BIGINT UNSIGNED NOT NULL,
  estado ENUM('activo','archivado') NOT NULL DEFAULT 'activo',
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (id_empresa) REFERENCES org_empresas(id) ON DELETE CASCADE,
  FOREIGN KEY (id_fuente) REFERENCES research_fuentes(id) ON DELETE CASCADE,
  FOREIGN KEY (creado_por) REFERENCES org_usuarios(id),
  INDEX idx_research_experiencia_tenant_fuente (id_empresa,id_fuente,estado,fecha_experiencia)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Recetas globales iniciales: orientan al usuario sin ejecutar acciones automáticas.
INSERT INTO research_recetas
(id_empresa,id_fuente,codigo_modo_acceso,uuid_publico,nombre,descripcion,condicion_cierre,version,activo,creado_por,creado_en,actualizado_en)
VALUES
(NULL,NULL,'MA-01','12000000-0000-4000-8000-000000000001','Consulta reproducible en buscador público','Preparar filtros, ejecutar manualmente y registrar el resultado exacto.','Consulta registrada con filtros, URL, fecha y comentario de resultado.','1.0',1,NULL,NOW(),NOW()),
(NULL,NULL,'MA-02','12000000-0000-4000-8000-000000000002','Importación desde API o descarga oficial','Verificar licencia, versión y estructura antes de importar datos oficiales.','Archivo o respuesta conservada con versión, parámetros y hash cuando aplique.','1.0',1,NULL,NOW(),NOW()),
(NULL,NULL,'MA-03','12000000-0000-4000-8000-000000000003','Revisión de PDF, catálogo o inventario','Identificar versión del documento, cobertura y referencias exactas.','Resultado registrado con página, fila, fragmento o signatura.','1.0',1,NULL,NOW(),NOW()),
(NULL,NULL,'MA-04','12000000-0000-4000-8000-000000000004','Solicitud mediante formulario web','Preparar datos y anexos, revisar y confirmar el envío humano.','Comprobante y copia de los datos enviados vinculados al caso.','1.0',1,NULL,NOW(),NOW()),
(NULL,NULL,'MA-05','12000000-0000-4000-8000-000000000005','Solicitud institucional por correo','Preparar un borrador verificable, anexos y plazo de seguimiento.','Mensaje aprobado, enviado y registrado con fecha y destinatario.','1.0',1,NULL,NOW(),NOW()),
(NULL,NULL,'MA-06','12000000-0000-4000-8000-000000000006','Consulta con cuenta del usuario','Recordar que la cuenta y las credenciales permanecen fuera de GeneaCase.','Consulta registrada sin contraseña, cookie ni token.','1.0',1,NULL,NOW(),NOW()),
(NULL,NULL,'MA-07','12000000-0000-4000-8000-000000000007','Gestión de CAPTCHA o restricción técnica','Detener automatización y crear una tarea manual o alternativa autorizada.','Bloqueo documentado y próxima acción segura definida.','1.0',1,NULL,NOW(),NOW()),
(NULL,NULL,'MA-08','12000000-0000-4000-8000-000000000008','Encargo para consulta física','Preparar alcance, referencias, costo máximo y evidencia esperada.','Entrega recibida y revisada con responsable, fecha y material verificable.','1.0',1,NULL,NOW(),NOW())
ON DUPLICATE KEY UPDATE nombre=VALUES(nombre),descripcion=VALUES(descripcion),condicion_cierre=VALUES(condicion_cierre),version=VALUES(version),activo=1;

UPDATE research_recetas SET
  nombre_en=CASE uuid_publico
    WHEN '12000000-0000-4000-8000-000000000001' THEN 'Reproducible public search'
    WHEN '12000000-0000-4000-8000-000000000002' THEN 'Official API or download import'
    WHEN '12000000-0000-4000-8000-000000000003' THEN 'PDF, catalogue or inventory review'
    WHEN '12000000-0000-4000-8000-000000000004' THEN 'Web form request'
    WHEN '12000000-0000-4000-8000-000000000005' THEN 'Institutional email request'
    WHEN '12000000-0000-4000-8000-000000000006' THEN 'User-account consultation'
    WHEN '12000000-0000-4000-8000-000000000007' THEN 'CAPTCHA or technical restriction handling'
    WHEN '12000000-0000-4000-8000-000000000008' THEN 'Physical consultation assignment'
    ELSE nombre_en END,
  descripcion_en=CASE uuid_publico
    WHEN '12000000-0000-4000-8000-000000000001' THEN 'Prepare filters, run the search manually and record the exact result.'
    WHEN '12000000-0000-4000-8000-000000000002' THEN 'Verify licence, version and structure before importing official data.'
    WHEN '12000000-0000-4000-8000-000000000003' THEN 'Identify the document version, coverage and exact references.'
    WHEN '12000000-0000-4000-8000-000000000004' THEN 'Prepare data and attachments, review them and confirm the human submission.'
    WHEN '12000000-0000-4000-8000-000000000005' THEN 'Prepare a verifiable draft, attachments and follow-up deadline.'
    WHEN '12000000-0000-4000-8000-000000000006' THEN 'Keep the account and credentials outside GeneaCase.'
    WHEN '12000000-0000-4000-8000-000000000007' THEN 'Stop automation and create a manual task or authorised alternative.'
    WHEN '12000000-0000-4000-8000-000000000008' THEN 'Prepare scope, references, maximum cost and expected evidence.'
    ELSE descripcion_en END,
  condicion_cierre_en=CASE uuid_publico
    WHEN '12000000-0000-4000-8000-000000000001' THEN 'Search recorded with filters, URL, date and result comment.'
    WHEN '12000000-0000-4000-8000-000000000002' THEN 'File or response preserved with version, parameters and hash when applicable.'
    WHEN '12000000-0000-4000-8000-000000000003' THEN 'Result recorded with page, row, excerpt or reference.'
    WHEN '12000000-0000-4000-8000-000000000004' THEN 'Receipt and copy of submitted data linked to the case.'
    WHEN '12000000-0000-4000-8000-000000000005' THEN 'Approved message sent and recorded with date and recipient.'
    WHEN '12000000-0000-4000-8000-000000000006' THEN 'Search recorded without password, cookie or token.'
    WHEN '12000000-0000-4000-8000-000000000007' THEN 'Block documented and a safe next action defined.'
    WHEN '12000000-0000-4000-8000-000000000008' THEN 'Delivery received and reviewed with responsible person, date and verifiable material.'
    ELSE condicion_cierre_en END
WHERE id_empresa IS NULL AND uuid_publico LIKE '12000000-0000-4000-8000-%';

INSERT INTO research_receta_pasos(id_receta,orden,titulo,instruccion,evidencia_esperada,advertencia,requiere_confirmacion_humana,activo)
SELECT id,1,'Definir alcance','Anotar persona, periodo, lugar, colección y condición de cierre antes de abrir la fuente.','Criterios de búsqueda documentados.','No asumir que una colección cubre todo un territorio o periodo.',1,1 FROM research_recetas WHERE uuid_publico='12000000-0000-4000-8000-000000000001'
ON DUPLICATE KEY UPDATE titulo=VALUES(titulo),instruccion=VALUES(instruccion),evidencia_esperada=VALUES(evidencia_esperada),advertencia=VALUES(advertencia),activo=1;
INSERT INTO research_receta_pasos(id_receta,orden,titulo,instruccion,evidencia_esperada,advertencia,requiere_confirmacion_humana,activo)
SELECT id,2,'Ejecutar y capturar parámetros','Usar el buscador público respetando sus condiciones y registrar la consulta exacta y filtros.','URL, fecha, consulta y filtros.','No automatizar masivamente ni copiar contenido no autorizado.',1,1 FROM research_recetas WHERE uuid_publico='12000000-0000-4000-8000-000000000001'
ON DUPLICATE KEY UPDATE titulo=VALUES(titulo),instruccion=VALUES(instruccion),evidencia_esperada=VALUES(evidencia_esperada),advertencia=VALUES(advertencia),activo=1;
INSERT INTO research_receta_pasos(id_receta,orden,titulo,instruccion,evidencia_esperada,advertencia,requiere_confirmacion_humana,activo)
SELECT id,3,'Clasificar resultado','Registrar hallazgo, parcial, negativo, falso positivo o bloqueo con comentario mínimo.','Resultado reproducible y próxima acción.','Un resultado negativo no demuestra ausencia.',1,1 FROM research_recetas WHERE uuid_publico='12000000-0000-4000-8000-000000000001'
ON DUPLICATE KEY UPDATE titulo=VALUES(titulo),instruccion=VALUES(instruccion),evidencia_esperada=VALUES(evidencia_esperada),advertencia=VALUES(advertencia),activo=1;

-- Pasos mínimos de los otros siete modos; cada uno exige confirmación humana.
INSERT INTO research_receta_pasos(id_receta,orden,titulo,instruccion,evidencia_esperada,advertencia,requiere_confirmacion_humana,activo)
SELECT r.id,s.orden,s.titulo,s.instruccion,s.evidencia,s.advertencia,1,1
FROM research_recetas r
JOIN (
  SELECT 'MA-02' modo,1 orden,'Verificar fuente oficial' titulo,'Confirmar endpoint, licencia, versión y formato publicado.' instruccion,'URL y metadatos oficiales.' evidencia,'No usar copias de origen incierto.' advertencia UNION ALL
  SELECT 'MA-02',2,'Descargar o consultar','Registrar parámetros y conservar el archivo o respuesta sin alterarlo.','Archivo/respuesta y hash.','No perder la versión consultada.' UNION ALL
  SELECT 'MA-02',3,'Validar importación','Comparar conteos, campos y errores antes de vincular resultados.','Reporte de importación revisado.','La importación no confirma identidades.' UNION ALL
  SELECT 'MA-03',1,'Identificar documento','Registrar título, versión, fecha, cobertura y procedencia.','Ficha del catálogo o PDF.','Evitar trabajar sobre una copia sin origen.' UNION ALL
  SELECT 'MA-03',2,'Localizar referencia','Buscar y conservar página, fila, fragmento o signatura exacta.','Referencia puntual reproducible.','No citar solo el nombre del archivo.' UNION ALL
  SELECT 'MA-03',3,'Registrar límites','Anotar lagunas, periodos no cubiertos y calidad de lectura.','Limitaciones metodológicas.','Un índice incompleto no prueba ausencia.' UNION ALL
  SELECT 'MA-04',1,'Preparar solicitud','Reunir datos y anexos sin incluir información innecesaria.','Borrador y lista de anexos.','Revisar datos de personas vivas.' UNION ALL
  SELECT 'MA-04',2,'Confirmar envío','El usuario revisa y envía el formulario desde el portal autorizado.','Comprobante o número de solicitud.','GeneaCase no debe enviar sin confirmación.' UNION ALL
  SELECT 'MA-04',3,'Programar seguimiento','Registrar plazo esperado y fecha de revisión.','Tarea y fecha de seguimiento.','No duplicar solicitudes vigentes.' UNION ALL
  SELECT 'MA-05',1,'Preparar borrador','Usar únicamente hechos aprobados y marcar hipótesis.','Destinatario, asunto, cuerpo y anexos.','No presentar hipótesis como hechos.' UNION ALL
  SELECT 'MA-05',2,'Revisar y enviar','El usuario confirma destinatario, contenido y anexos antes del envío.','Copia del mensaje enviado.','No enviar automáticamente.' UNION ALL
  SELECT 'MA-05',3,'Registrar respuesta','Vincular respuesta, fecha y acciones pendientes.','Respuesta y próxima acción.','Conservar el contexto del hilo.' UNION ALL
  SELECT 'MA-06',1,'Abrir portal externo','El usuario inicia sesión directamente con su propia cuenta.','Nombre del portal y fecha.','No guardar credenciales ni cookies.' UNION ALL
  SELECT 'MA-06',2,'Ejecutar consulta','Registrar parámetros usados sin copiar datos restringidos indebidamente.','Consulta, filtros y referencia permitida.','Respetar suscripción y términos.' UNION ALL
  SELECT 'MA-06',3,'Cerrar sesión y registrar','Finalizar la sesión externa y guardar solo el resultado permitido.','Resultado y próxima acción.','No compartir acceso entre usuarios.' UNION ALL
  SELECT 'MA-07',1,'Detener automatización','Identificar CAPTCHA, bloqueo, robots o restricción técnica.','Control detectado y fecha.','No intentar evadir el control.' UNION ALL
  SELECT 'MA-07',2,'Definir alternativa','Crear tarea manual, solicitar acceso, buscar API o contactar a la institución.','Alternativa autorizada.','No usar técnicas anti-bot.' UNION ALL
  SELECT 'MA-07',3,'Registrar resultado manual','Una persona autorizada captura el resultado permitido.','Resultado y evidencia autorizada.','Minimizar datos capturados.' UNION ALL
  SELECT 'MA-08',1,'Preparar encargo','Definir institución, signaturas, nombres, variantes, periodo y presupuesto.','Paquete de instrucciones.','No enviar documentos privados innecesarios.' UNION ALL
  SELECT 'MA-08',2,'Asignar responsable','Registrar investigador, plazo, costo y condiciones de entrega.','Responsable y condiciones aceptadas.','Aplicar acceso temporal y mínimo.' UNION ALL
  SELECT 'MA-08',3,'Revisar entrega','Comprobar procedencia, páginas, fotografías, signaturas y recibos.','Material recibido y validación.','Una entrega sin referencia exacta no cierra la búsqueda.'
) s ON s.modo=r.codigo_modo_acceso
WHERE r.id_empresa IS NULL AND r.id_fuente IS NULL AND r.codigo_modo_acceso<>'MA-01'
ON DUPLICATE KEY UPDATE titulo=VALUES(titulo),instruccion=VALUES(instruccion),evidencia_esperada=VALUES(evidencia_esperada),advertencia=VALUES(advertencia),activo=1;

UPDATE research_receta_pasos p
JOIN research_recetas r ON r.id=p.id_receta AND r.id_empresa IS NULL
SET
 p.titulo_en=CASE CONCAT(r.codigo_modo_acceso,':',p.orden)
  WHEN 'MA-01:1' THEN 'Define scope' WHEN 'MA-01:2' THEN 'Run and capture parameters' WHEN 'MA-01:3' THEN 'Classify result'
  WHEN 'MA-02:1' THEN 'Verify official source' WHEN 'MA-02:2' THEN 'Download or query' WHEN 'MA-02:3' THEN 'Validate import'
  WHEN 'MA-03:1' THEN 'Identify document' WHEN 'MA-03:2' THEN 'Locate reference' WHEN 'MA-03:3' THEN 'Record limitations'
  WHEN 'MA-04:1' THEN 'Prepare request' WHEN 'MA-04:2' THEN 'Confirm submission' WHEN 'MA-04:3' THEN 'Schedule follow-up'
  WHEN 'MA-05:1' THEN 'Prepare draft' WHEN 'MA-05:2' THEN 'Review and send' WHEN 'MA-05:3' THEN 'Record reply'
  WHEN 'MA-06:1' THEN 'Open external portal' WHEN 'MA-06:2' THEN 'Run query' WHEN 'MA-06:3' THEN 'Sign out and record'
  WHEN 'MA-07:1' THEN 'Stop automation' WHEN 'MA-07:2' THEN 'Define alternative' WHEN 'MA-07:3' THEN 'Record manual result'
  WHEN 'MA-08:1' THEN 'Prepare assignment' WHEN 'MA-08:2' THEN 'Assign responsible person' WHEN 'MA-08:3' THEN 'Review delivery'
  ELSE p.titulo_en END,
 p.instruccion_en=CASE CONCAT(r.codigo_modo_acceso,':',p.orden)
  WHEN 'MA-01:1' THEN 'Record person, period, place, collection and closing condition before opening the source.'
  WHEN 'MA-01:2' THEN 'Use the public search in accordance with its terms and record the exact query and filters.'
  WHEN 'MA-01:3' THEN 'Record finding, partial, negative, false positive or block with a minimum comment.'
  WHEN 'MA-02:1' THEN 'Confirm endpoint, licence, version and published format.'
  WHEN 'MA-02:2' THEN 'Record parameters and preserve the file or response unchanged.'
  WHEN 'MA-02:3' THEN 'Compare counts, fields and errors before linking results.'
  WHEN 'MA-03:1' THEN 'Record title, version, date, coverage and provenance.'
  WHEN 'MA-03:2' THEN 'Search and preserve the exact page, row, excerpt or reference.'
  WHEN 'MA-03:3' THEN 'Record gaps, uncovered periods and reading quality.'
  WHEN 'MA-04:1' THEN 'Gather data and attachments without including unnecessary information.'
  WHEN 'MA-04:2' THEN 'The user reviews and submits the form through the authorised portal.'
  WHEN 'MA-04:3' THEN 'Record the expected deadline and review date.'
  WHEN 'MA-05:1' THEN 'Use only approved facts and mark hypotheses.'
  WHEN 'MA-05:2' THEN 'The user confirms recipient, content and attachments before sending.'
  WHEN 'MA-05:3' THEN 'Link the reply, date and pending actions.'
  WHEN 'MA-06:1' THEN 'The user signs in directly with their own account.'
  WHEN 'MA-06:2' THEN 'Record the parameters used without improperly copying restricted data.'
  WHEN 'MA-06:3' THEN 'Close the external session and save only the permitted result.'
  WHEN 'MA-07:1' THEN 'Identify CAPTCHA, block, robots control or technical restriction.'
  WHEN 'MA-07:2' THEN 'Create a manual task, request access, find an API or contact the institution.'
  WHEN 'MA-07:3' THEN 'An authorised person captures the permitted result.'
  WHEN 'MA-08:1' THEN 'Define institution, references, names, variants, period and budget.'
  WHEN 'MA-08:2' THEN 'Record researcher, deadline, cost and delivery conditions.'
  WHEN 'MA-08:3' THEN 'Check provenance, pages, photographs, references and receipts.'
  ELSE p.instruccion_en END,
 p.evidencia_esperada_en=CASE CONCAT(r.codigo_modo_acceso,':',p.orden)
  WHEN 'MA-01:1' THEN 'Documented search criteria.' WHEN 'MA-01:2' THEN 'URL, date, query and filters.' WHEN 'MA-01:3' THEN 'Reproducible result and next action.'
  WHEN 'MA-02:1' THEN 'Official URL and metadata.' WHEN 'MA-02:2' THEN 'File or response and hash.' WHEN 'MA-02:3' THEN 'Reviewed import report.'
  WHEN 'MA-03:1' THEN 'Catalogue or PDF record.' WHEN 'MA-03:2' THEN 'Reproducible exact reference.' WHEN 'MA-03:3' THEN 'Methodological limitations.'
  WHEN 'MA-04:1' THEN 'Draft and attachment list.' WHEN 'MA-04:2' THEN 'Receipt or request number.' WHEN 'MA-04:3' THEN 'Task and follow-up date.'
  WHEN 'MA-05:1' THEN 'Recipient, subject, body and attachments.' WHEN 'MA-05:2' THEN 'Copy of the sent message.' WHEN 'MA-05:3' THEN 'Reply and next action.'
  WHEN 'MA-06:1' THEN 'Portal name and date.' WHEN 'MA-06:2' THEN 'Query, filters and permitted reference.' WHEN 'MA-06:3' THEN 'Result and next action.'
  WHEN 'MA-07:1' THEN 'Detected control and date.' WHEN 'MA-07:2' THEN 'Authorised alternative.' WHEN 'MA-07:3' THEN 'Result and authorised evidence.'
  WHEN 'MA-08:1' THEN 'Instruction package.' WHEN 'MA-08:2' THEN 'Responsible person and accepted conditions.' WHEN 'MA-08:3' THEN 'Received material and validation.'
  ELSE p.evidencia_esperada_en END,
 p.advertencia_en=CASE CONCAT(r.codigo_modo_acceso,':',p.orden)
  WHEN 'MA-01:1' THEN 'Do not assume that a collection covers an entire territory or period.'
  WHEN 'MA-01:2' THEN 'Do not automate at scale or copy unauthorised content.'
  WHEN 'MA-01:3' THEN 'A negative result does not prove absence.'
  WHEN 'MA-02:1' THEN 'Do not use copies of uncertain origin.' WHEN 'MA-02:2' THEN 'Do not lose the consulted version.' WHEN 'MA-02:3' THEN 'Importing does not confirm identities.'
  WHEN 'MA-03:1' THEN 'Avoid working on a copy without provenance.' WHEN 'MA-03:2' THEN 'Do not cite only the file name.' WHEN 'MA-03:3' THEN 'An incomplete index does not prove absence.'
  WHEN 'MA-04:1' THEN 'Review data concerning living people.' WHEN 'MA-04:2' THEN 'GeneaCase must not submit without confirmation.' WHEN 'MA-04:3' THEN 'Do not duplicate active requests.'
  WHEN 'MA-05:1' THEN 'Do not present hypotheses as facts.' WHEN 'MA-05:2' THEN 'Do not send automatically.' WHEN 'MA-05:3' THEN 'Preserve the thread context.'
  WHEN 'MA-06:1' THEN 'Do not store credentials or cookies.' WHEN 'MA-06:2' THEN 'Respect the subscription and terms.' WHEN 'MA-06:3' THEN 'Do not share access between users.'
  WHEN 'MA-07:1' THEN 'Do not attempt to bypass the control.' WHEN 'MA-07:2' THEN 'Do not use anti-bot techniques.' WHEN 'MA-07:3' THEN 'Minimise captured data.'
  WHEN 'MA-08:1' THEN 'Do not send unnecessary private documents.' WHEN 'MA-08:2' THEN 'Apply temporary and minimum access.' WHEN 'MA-08:3' THEN 'A delivery without an exact reference does not close the search.'
  ELSE p.advertencia_en END
WHERE r.uuid_publico LIKE '12000000-0000-4000-8000-%';

INSERT INTO org_permisos(codigo,modulo,nombre,descripcion) VALUES
('research.directory.view','research','Ver directorio de fuentes','Consulta fuentes globales y propias, modos de acceso, recetas y cobertura de la organización.'),
('research.directory.manage','research','Administrar directorio de fuentes','Crea y actualiza fuentes propias, canales, recetas y experiencias internas.')
ON DUPLICATE KEY UPDATE modulo=VALUES(modulo),nombre=VALUES(nombre),descripcion=VALUES(descripcion);

INSERT IGNORE INTO org_roles_permisos(id_rol,id_permiso)
SELECT r.id,p.id FROM org_roles r JOIN org_permisos p ON p.codigo='research.directory.view'
WHERE r.codigo IN ('owner_plataforma','admin_empresa','investigador','colaborador','revisor','investigador_local');

INSERT IGNORE INTO org_roles_permisos(id_rol,id_permiso)
SELECT r.id,p.id FROM org_roles r JOIN org_permisos p ON p.codigo='research.directory.manage'
WHERE r.codigo IN ('owner_plataforma','admin_empresa','investigador');
