-- Validaciones manuales para la migracion conservadora a document_series.
-- No modifica datos.

-- 1. Series duplicadas de issued_invoice tras la migracion legacy.
SELECT
  company_id,
  document_type,
  code,
  COUNT(*) AS duplicated_rows
FROM document_series
WHERE document_type = 'issued_invoice'
GROUP BY company_id, document_type, code
HAVING COUNT(*) > 1;

-- 2. Empresas activas sin serie default de proforma.
SELECT c.id AS company_id
FROM companies c
LEFT JOIN document_series ds
  ON ds.company_id = c.id
 AND ds.document_type = 'proforma'
 AND ds.is_default = TRUE
 AND ds.deleted_at IS NULL
WHERE c.status = 'active'
GROUP BY c.id
HAVING COUNT(ds.id) = 0;

-- 3. Duplicados logicos por company/type/code.
SELECT
  company_id,
  document_type,
  code,
  COUNT(*) AS duplicated_rows
FROM document_series
WHERE deleted_at IS NULL
GROUP BY company_id, document_type, code
HAVING COUNT(*) > 1;

-- 4. Contadores invalidos.
SELECT
  id,
  company_id,
  document_type,
  code,
  next_number,
  padding
FROM document_series
WHERE next_number < 1
   OR padding < 1;

-- 5. Ventanas de vigencia incoherentes.
SELECT
  id,
  company_id,
  document_type,
  code,
  valid_from,
  valid_to
FROM document_series
WHERE valid_from IS NOT NULL
  AND valid_to IS NOT NULL
  AND valid_from > valid_to;

-- 6. Proformas sin referencia visible.
SELECT
  id,
  company_id,
  document_series_id,
  proforma_number,
  proforma_reference
FROM proformas
WHERE proforma_reference IS NULL
   OR TRIM(proforma_reference) = '';
