REVOKE ALL ON FUNCTION condon.create_usage_record_v2(
  uuid,
  uuid,
  uuid,
  varchar,
  date,
  date,
  varchar,
  smallint,
  text,
  uuid
) FROM PUBLIC;
REVOKE ALL ON FUNCTION condon.ensure_booking_for_usage() FROM PUBLIC;

DROP FUNCTION condon.create_usage_record_v2(
  uuid,
  uuid,
  uuid,
  varchar,
  date,
  date,
  varchar,
  smallint,
  text,
  uuid
);
DROP TRIGGER usage_records_booking_trg ON condon.usage_records;
DROP FUNCTION condon.ensure_booking_for_usage();

DROP INDEX condon.usage_records_source_location_key;
DROP INDEX condon.bookings_created_idx;

ALTER TABLE condon.usage_records
  DROP CONSTRAINT usage_records_confirmation_booking_fk,
  DROP CONSTRAINT usage_records_room_count_check,
  DROP CONSTRAINT usage_records_source_location_check,
  DROP CONSTRAINT usage_records_multiplier_check,
  DROP CONSTRAINT usage_records_use_nights_check,
  DROP CONSTRAINT usage_records_balance_check;

ALTER TABLE condon.usage_records
  DROP COLUMN import_batch,
  DROP COLUMN source_sequence,
  DROP COLUMN source_row,
  DROP COLUMN source_sheet,
  DROP COLUMN room_count,
  DROP COLUMN raw_used_room_type;

ALTER TABLE condon.usage_records
  ALTER COLUMN used_room_type_code SET NOT NULL,
  ALTER COLUMN applied_multiplier SET NOT NULL;

ALTER TABLE condon.usage_records
  ADD CONSTRAINT usage_records_confirmation_no_key UNIQUE (confirmation_no),
  ADD CONSTRAINT usage_records_multiplier_check
    CHECK (applied_multiplier BETWEEN 1 AND 3),
  ADD CONSTRAINT usage_records_use_nights_check
    CHECK (
      use_nights = night_count * applied_multiplier
      AND use_nights > 0
    ),
  ADD CONSTRAINT usage_records_balance_check
    CHECK (
      balance_before >= use_nights
      AND balance_after = balance_before - use_nights
      AND balance_after >= 0
    );

DROP TABLE condon.bookings;
