import {
	index,
	integer,
	sqliteTable,
	text,
	uniqueIndex,
} from "drizzle-orm/sqlite-core";
import type { SeriesStatus } from "../enums";
import { titles } from "./titles";

export const series = sqliteTable(
	"series",
	{
		id: text("id")
			.primaryKey()
			.$defaultFn(() => {
				return Bun.randomUUIDv7();
			}),
		titleId: text("title_id")
			.notNull()
			.unique()
			.references(() => titles.id, { onDelete: "cascade" }),
		status: text("status").$type<SeriesStatus>(), // "RETURNING" | "ENDED" | ...
		createdAt: integer("created_at", { mode: "timestamp" })
			.$defaultFn(() => new Date())
			.notNull(),
		updatedAt: integer("updated_at", { mode: "timestamp" })
			.$defaultFn(() => new Date())
			.$onUpdate(() => new Date())
			.notNull(),
	},
	(t) => [index("idx_series_title").on(t.titleId)],
);

// ----- SEASONS (child of series) -----
export const seasons = sqliteTable(
	"seasons",
	{
		id: text("id")
			.primaryKey()
			.$defaultFn(() => {
				return Bun.randomUUIDv7();
			}),
		seriesId: text("series_id")
			.notNull()
			.references(() => series.id, { onDelete: "cascade" }),
		seasonNumber: integer("season_number").notNull(),
		title: text("title"), // opsional, kadang S1 punya judul
		createdAt: integer("created_at", { mode: "timestamp" })
			.$defaultFn(() => new Date())
			.notNull(),
	},
	(t) => [
		uniqueIndex("ux_seasons_series_number").on(t.seriesId, t.seasonNumber),
		index("idx_seasons_series").on(t.seriesId),
	],
);

// ----- EPISODES (child of seasons) -----
export const episodes = sqliteTable(
	"episodes",
	{
		id: text("id")
			.primaryKey()
			.$defaultFn(() => {
				return Bun.randomUUIDv7();
			}),
		seriesId: text("series_id")
			.notNull()
			.references(() => series.id, { onDelete: "cascade" }),
		seasonId: text("season_id")
			.notNull()
			.references(() => seasons.id, { onDelete: "cascade" }),
		seasonNumber: integer("season_number").notNull(),
		episodeNumber: integer("episode_number").notNull(),
		title: text("title").notNull(),
		overview: text("overview"),
		airDate: text("air_date"),
		runtimeSeconds: integer("runtime_seconds"),
		backgroundPath: text("background_path"),
		createdAt: integer("created_at", { mode: "timestamp" })
			.$defaultFn(() => new Date())
			.notNull(),
	},
	(t) => [
		uniqueIndex("ux_eps_series_s_e").on(
			t.seriesId,
			t.seasonNumber,
			t.episodeNumber,
		),
		index("idx_eps_season").on(t.seasonId),
		index("idx_eps_series").on(t.seriesId),
	],
);
