CREATE TYPE "public"."watch_history_source" AS ENUM('plex', 'manual');--> statement-breakpoint
CREATE TABLE "watch_history" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"user_id" uuid NOT NULL,
	"media_item_id" uuid NOT NULL,
	"season_number" integer,
	"episode_number" integer,
	"watched_at" timestamp NOT NULL,
	"source" "watch_history_source" DEFAULT 'plex' NOT NULL,
	"plex_history_key" text,
	"plex_rating_key" text,
	"created_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "watch_history" ADD CONSTRAINT "watch_history_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "watch_history" ADD CONSTRAINT "watch_history_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "public"."media_items"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "watch_history_user_plex_key_idx" ON "watch_history" USING btree ("user_id","plex_history_key") WHERE plex_history_key is not null;--> statement-breakpoint
CREATE INDEX "watch_history_user_watched_idx" ON "watch_history" USING btree ("user_id","watched_at" DESC NULLS LAST);