-- Permit same-day (zero-night) processed Finance records while preserving exact date arithmetic.
-- PostgreSQL 15+
-- Target database: booking_test.

BEGIN;

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
        )
    );

COMMENT ON CONSTRAINT daily_records_dates_and_nights_valid
    ON finance.daily_records IS
  'Allows processed same-day records with zero nights; rejects negative stays and any date/night mismatch.';

COMMIT;
