CREATE TABLE "interest_berths" (
	"id" text PRIMARY KEY NOT NULL,
	"interest_id" text NOT NULL,
	"berth_id" text NOT NULL,
	"is_primary" boolean DEFAULT false NOT NULL,
	"is_specific_interest" boolean DEFAULT true NOT NULL,
	"is_in_eoi_bundle" boolean DEFAULT false NOT NULL,
	"eoi_bypass_reason" text,
	"eoi_bypassed_by" text,
	"eoi_bypassed_at" timestamp with time zone,
	"added_by" text,
	"added_at" timestamp with time zone DEFAULT now() NOT NULL,
	"notes" text
);
--> statement-breakpoint
ALTER TABLE "interests" ADD COLUMN "desired_length_ft" numeric;--> statement-breakpoint
ALTER TABLE "interests" ADD COLUMN "desired_width_ft" numeric;--> statement-breakpoint
ALTER TABLE "interests" ADD COLUMN "desired_draft_ft" numeric;--> statement-breakpoint
ALTER TABLE "interest_berths" ADD CONSTRAINT "interest_berths_interest_id_interests_id_fk" FOREIGN KEY ("interest_id") REFERENCES "public"."interests"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "interest_berths" ADD CONSTRAINT "interest_berths_berth_id_berths_id_fk" FOREIGN KEY ("berth_id") REFERENCES "public"."berths"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "idx_ib_interest_berth" ON "interest_berths" USING btree ("interest_id","berth_id");--> statement-breakpoint
CREATE UNIQUE INDEX "idx_ib_one_primary" ON "interest_berths" USING btree ("interest_id") WHERE "interest_berths"."is_primary" = true;--> statement-breakpoint
CREATE INDEX "idx_ib_berth" ON "interest_berths" USING btree ("berth_id");--> statement-breakpoint
CREATE INDEX "idx_ib_specific" ON "interest_berths" USING btree ("berth_id") WHERE "interest_berths"."is_specific_interest" = true;--> statement-breakpoint
-- Pre-flight: halt if any interests.berth_id points at a row that no
-- longer exists. The new junction's FK is `restrict`, so a dangling
-- value would otherwise abort the insert mid-batch with a confusing
-- error.
DO $$
DECLARE
  orphan_count integer;
BEGIN
  SELECT count(*) INTO orphan_count
  FROM interests i
  LEFT JOIN berths b ON b.id = i.berth_id
  WHERE i.berth_id IS NOT NULL
    AND b.id IS NULL;
  IF orphan_count > 0 THEN
    RAISE EXCEPTION 'interests.berth_id has % dangling references; resolve manually before re-running', orphan_count;
  END IF;
END $$;--> statement-breakpoint
-- Migrate existing interest.berth_id values into the junction. Every
-- pre-existing single-berth link becomes a primary, specific-interest
-- row. is_in_eoi_bundle = true only when the interest already has a
-- signed EOI (the legacy "the berth is contractually committed" case).
INSERT INTO interest_berths (
  id, interest_id, berth_id,
  is_primary, is_specific_interest, is_in_eoi_bundle,
  added_at
)
SELECT
  gen_random_uuid()::text,
  i.id,
  i.berth_id,
  true,
  true,
  COALESCE(i.eoi_status = 'signed', false),
  i.created_at
FROM interests i
WHERE i.berth_id IS NOT NULL
ON CONFLICT (interest_id, berth_id) DO NOTHING;