CREATE TABLE IF NOT EXISTS "sports_season_tournaments" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"sports_season_id" uuid NOT NULL,
	"tournament_id" uuid NOT NULL,
	"created_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
DO $$ BEGIN
 ALTER TABLE "sports_season_tournaments" ADD CONSTRAINT "sports_season_tournaments_sports_season_id_sports_seasons_id_fk" FOREIGN KEY ("sports_season_id") REFERENCES "public"."sports_seasons"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
 WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
 ALTER TABLE "sports_season_tournaments" ADD CONSTRAINT "sports_season_tournaments_tournament_id_tournaments_id_fk" FOREIGN KEY ("tournament_id") REFERENCES "public"."tournaments"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
 WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
CREATE UNIQUE INDEX IF NOT EXISTS "sports_season_tournaments_unique" ON "sports_season_tournaments" USING btree ("sports_season_id","tournament_id");
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "sports_season_tournaments_tournament_id_idx" ON "sports_season_tournaments" USING btree ("tournament_id");
--> statement-breakpoint
-- Backfill: seed from existing scoring_events that already associate tournaments with sports seasons
INSERT INTO "sports_season_tournaments" ("sports_season_id", "tournament_id")
SELECT DISTINCT "sports_season_id", "tournament_id"
FROM "scoring_events"
WHERE "tournament_id" IS NOT NULL
ON CONFLICT DO NOTHING;