BEGIN;

ALTER TABLE laying_transfers
    ADD COLUMN IF NOT EXISTS effective_move_date DATE,
    ADD COLUMN IF NOT EXISTS executed_at TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS executed_by BIGINT;

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'users')
        AND NOT EXISTS (
            SELECT 1
            FROM pg_constraint
            WHERE conname = 'fk_laying_transfers_executed_by'
        ) THEN
        ALTER TABLE laying_transfers
            ADD CONSTRAINT fk_laying_transfers_executed_by
            FOREIGN KEY (executed_by)
            REFERENCES users(id)
            ON DELETE SET NULL
            ON UPDATE CASCADE;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_laying_transfers_effective_move_date
    ON laying_transfers(effective_move_date);

CREATE INDEX IF NOT EXISTS idx_laying_transfers_executed_at
    ON laying_transfers(executed_at);

CREATE INDEX IF NOT EXISTS idx_laying_transfers_executed_by
    ON laying_transfers(executed_by);

-- Backfill historical approved transfers. Before deferred execution,
-- approved transfers were executed immediately during approval.
UPDATE laying_transfers lt
SET
    effective_move_date = COALESCE(lt.effective_move_date, lt.transfer_date),
    executed_at = COALESCE(lt.executed_at, lt.updated_at),
    executed_by = COALESCE(lt.executed_by, lt.created_by)
WHERE (
    SELECT a.action
    FROM approvals a
    WHERE a.approvable_type = 'TRANSFER_TO_LAYINGS'
      AND a.approvable_id = lt.id
    ORDER BY a.id DESC
    LIMIT 1
) = 'APPROVED';

COMMIT;
