SELECT 1; /* MIGRACION 124: Auditoria base para edicion de pagos en commerce.pagos_planes | Fecha: 2026-03-26 | Plan: 093 */

ALTER TABLE commerce.pagos_planes
    ADD COLUMN IF NOT EXISTS registered_by_login_id INTEGER;

ALTER TABLE commerce.pagos_planes
    ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ;

ALTER TABLE commerce.pagos_planes
    ADD COLUMN IF NOT EXISTS updated_by_login_id INTEGER;

ALTER TABLE commerce.pagos_planes
    ADD COLUMN IF NOT EXISTS historial_cambios JSONB;

UPDATE commerce.pagos_planes
SET registered_by_login_id = created_by_login_id
WHERE registered_by_login_id IS NULL;

UPDATE commerce.pagos_planes
SET updated_at = COALESCE(updated_at, fecha_pago, NOW())
WHERE updated_at IS NULL;

UPDATE commerce.pagos_planes
SET historial_cambios = '[]'::jsonb
WHERE historial_cambios IS NULL;

ALTER TABLE commerce.pagos_planes
    ALTER COLUMN updated_at SET DEFAULT NOW();

ALTER TABLE commerce.pagos_planes
    ALTER COLUMN updated_at SET NOT NULL;

ALTER TABLE commerce.pagos_planes
    ALTER COLUMN historial_cambios SET DEFAULT '[]'::jsonb;

ALTER TABLE commerce.pagos_planes
    ALTER COLUMN historial_cambios SET NOT NULL;

COMMENT ON COLUMN commerce.pagos_planes.registered_by_login_id IS 'Login atribuible al registro de negocio del pago. Se backfillea desde created_by_login_id para filas legacy y queda listo para ser controlado por runtime sin alterar created_by_login_id.';

COMMENT ON COLUMN commerce.pagos_planes.updated_at IS 'Timestamp de ultima actualizacion funcional del pago. Se inicializa con fecha_pago para filas legacy y con NOW() para filas nuevas.';

COMMENT ON COLUMN commerce.pagos_planes.updated_by_login_id IS 'Login que realizo la ultima actualizacion funcional del pago.';

COMMENT ON COLUMN commerce.pagos_planes.historial_cambios IS 'Historial append-only de cambios del pago para auditoria funcional.';
