-- v4.3_facturapi.sql
-- Migrate CFDI timbrado from Horux360 XML pipeline to Facturapi JSON API.
--
-- Changes:
--   - Rename cfdi_queue.xml_unsigned -> payload_unsigned (stores Facturapi JSON payload)
--   - Keep xml_signed for the signed XML returned by Facturapi
--   - Add external_id column to store Facturapi invoice id
--   - Add facturapi config keys to tenant_config

-- ═════════════════════════════════════════════════════════════════════════════
-- 1. CFDI_QUEUE: adapt schema for Facturapi payloads
-- ═════════════════════════════════════════════════════════════════════════════
DO $$
BEGIN
    IF EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'cfdi_queue' AND column_name = 'xml_unsigned'
    ) THEN
        ALTER TABLE cfdi_queue RENAME COLUMN xml_unsigned TO payload_unsigned;
    END IF;
END $$;

COMMENT ON COLUMN cfdi_queue.payload_unsigned IS 'Facturapi JSON payload (previously unsigned XML for Horux)';
COMMENT ON COLUMN cfdi_queue.xml_signed IS 'Signed+stamped XML returned by Facturapi';

ALTER TABLE cfdi_queue ADD COLUMN IF NOT EXISTS external_id VARCHAR(64);
COMMENT ON COLUMN cfdi_queue.external_id IS 'Facturapi invoice id';

CREATE INDEX IF NOT EXISTS idx_cfdi_queue_external_id ON cfdi_queue(external_id);

-- ═════════════════════════════════════════════════════════════════════════════
-- 2. TENANT_CONFIG: Facturapi configuration keys
-- ═════════════════════════════════════════════════════════════════════════════
INSERT INTO tenant_config (key, value)
VALUES
    ('cfdi_facturapi_key', ''),
    ('cfdi_facturapi_org_id', ''),
    ('cfdi_facturapi_customer_sync', 'true')
ON CONFLICT (key) DO NOTHING;

-- Backward-compat: migrate old Horux keys to comments so they are not used anymore
COMMENT ON TABLE tenant_config IS 'tenant_config; old keys cfdi_horux_api_url and cfdi_horux_api_key are deprecated';
