-- DESTRUCTIVE rollback draft for migration 003.
-- Do not execute while a retained same-day/zero-night Finance record exists.
-- Target database: booking_test.

BEGIN;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM finance.daily_records
        WHERE arrival IS NOT NULL
          AND departure = arrival
          AND nights = 0
    ) THEN
        RAISE EXCEPTION
            'remove or migrate same-day zero-night records before rolling back migration 003';
    END IF;
END;
$$;

ALTER TABLE finance.daily_records
    DROP CONSTRAINT daily_records_dates_and_nights_valid;

ALTER TABLE finance.daily_records
    ADD CONSTRAINT daily_records_dates_and_nights_valid CHECK (
        arrival IS NULL
        OR departure IS NULL
        OR nights IS NULL
        OR (
            departure > arrival
            AND nights = departure - arrival
        )
    );

COMMIT;
