CREATE EXTENSION IF NOT EXISTS btree_gist;--> statement-breakpoint
CREATE TYPE "public"."inventory_lock_type" AS ENUM('booking', 'hold', 'block');--> statement-breakpoint
CREATE TABLE "inventory_locks" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"unit_id" uuid NOT NULL,
	"type" "inventory_lock_type" NOT NULL,
	"source_id" uuid NOT NULL,
	"check_in" date NOT NULL,
	"check_out" date NOT NULL,
	"active" boolean DEFAULT true NOT NULL,
	"expires_at" timestamp with time zone,
	"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "inventory_locks" ADD CONSTRAINT "inventory_locks_unit_id_units_id_fk" FOREIGN KEY ("unit_id") REFERENCES "public"."units"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "inventory_locks_source_unique" ON "inventory_locks" USING btree ("type","source_id");--> statement-breakpoint
CREATE INDEX "inventory_locks_unit_dates_idx" ON "inventory_locks" USING btree ("unit_id","check_in");--> statement-breakpoint
ALTER TABLE "inventory_locks" ADD CONSTRAINT "inventory_locks_valid_range" CHECK ("check_in" < "check_out");--> statement-breakpoint
ALTER TABLE "inventory_locks" ADD CONSTRAINT "inventory_locks_no_active_overlap" EXCLUDE USING gist (
  "unit_id" WITH =,
  daterange("check_in", "check_out", '[)') WITH &&
) WHERE ("active" = true);
