-- Moneda operativa por sucursal (Fase 1.1)
-- base_currency en companies = moneda funcional (consolidación)
-- operating_currency en branches = moneda con la que opera la sucursal

ALTER TABLE branches ADD COLUMN IF NOT EXISTS operating_currency VARCHAR(3) NULL;

UPDATE branches b
SET operating_currency = UPPER(c.base_currency)
FROM companies c
WHERE c.id = b.company_id
  AND (b.operating_currency IS NULL OR TRIM(b.operating_currency) = '');

ALTER TABLE branches
  ALTER COLUMN operating_currency SET DEFAULT 'USD';

UPDATE branches
SET operating_currency = 'USD'
WHERE operating_currency IS NULL OR TRIM(operating_currency) = '';

ALTER TABLE branches
  ALTER COLUMN operating_currency SET NOT NULL;

COMMENT ON COLUMN companies.base_currency IS 'Moneda funcional de la empresa (consolidación y reportes grupales)';
COMMENT ON COLUMN branches.operating_currency IS 'Moneda operativa de la sucursal (transacciones locales)';
