ALTER TABLE gene_fuentes
  ADD COLUMN IF NOT EXISTS notas TEXT NULL AFTER legibilidad,
  ADD COLUMN IF NOT EXISTS estado ENUM('activo','archivado') NOT NULL DEFAULT 'activo' AFTER notas;

ALTER TABLE gene_documentos
  ADD COLUMN IF NOT EXISTS categoria VARCHAR(120) NULL AFTER tipo,
  ADD COLUMN IF NOT EXISTS descripcion TEXT NULL AFTER categoria,
  ADD COLUMN IF NOT EXISTS numero_paginas INT UNSIGNED NULL AFTER objeto_original_id,
  MODIFY COLUMN estado ENUM('pendiente','recibido','en_revision','analizado','descartado','cargado','procesando','revisado','archivado','error') NOT NULL DEFAULT 'recibido';

CREATE TABLE IF NOT EXISTS gene_documento_personas (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  id_empresa BIGINT UNSIGNED NOT NULL,
  id_documento BIGINT UNSIGNED NOT NULL,
  id_persona BIGINT UNSIGNED NOT NULL,
  relacion VARCHAR(120) NOT NULL DEFAULT 'mencionada',
  creado_por BIGINT UNSIGNED NOT NULL,
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (id_empresa) REFERENCES org_empresas(id),
  FOREIGN KEY (id_documento) REFERENCES gene_documentos(id) ON DELETE CASCADE,
  FOREIGN KEY (id_persona) REFERENCES gene_personas(id),
  FOREIGN KEY (creado_por) REFERENCES org_usuarios(id),
  UNIQUE KEY uq_documento_persona (id_documento,id_persona),
  INDEX idx_documento_persona_tenant (id_empresa,id_persona)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS gene_documento_solicitudes (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  id_empresa BIGINT UNSIGNED NOT NULL,
  id_caso BIGINT UNSIGNED NOT NULL,
  uuid_publico CHAR(36) NOT NULL UNIQUE,
  id_persona BIGINT UNSIGNED NULL,
  titulo VARCHAR(300) NOT NULL,
  descripcion TEXT NULL,
  tipo_documento VARCHAR(120) NULL,
  solicitado_a VARCHAR(220) NULL,
  prioridad ENUM('baja','media','alta','critica') NOT NULL DEFAULT 'media',
  estado ENUM('pendiente','solicitado','recibido','no_disponible','descartado') NOT NULL DEFAULT 'pendiente',
  fecha_limite DATE NULL,
  creado_por BIGINT UNSIGNED NOT NULL,
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  completado_en DATETIME NULL,
  FOREIGN KEY (id_empresa) REFERENCES org_empresas(id),
  FOREIGN KEY (id_caso) REFERENCES gene_casos(id) ON DELETE CASCADE,
  FOREIGN KEY (id_persona) REFERENCES gene_personas(id),
  FOREIGN KEY (creado_por) REFERENCES org_usuarios(id),
  INDEX idx_doc_solicitud_caso_estado (id_empresa,id_caso,estado),
  INDEX idx_doc_solicitud_persona (id_empresa,id_persona)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
