import {
	index,
	integer,
	real,
	sqliteTable,
	text,
	uniqueIndex,
} from "drizzle-orm/sqlite-core";
import type { MediaParentType, StreamCodecType } from "./enums";
import { episodes, movies } from "./metadata";

/**
 * media_items = daftar file (path) yang playable:
 *  - parentType "MOVIE"  → movieId terisi
 *  - parentType "EPISODE"→ episodeId terisi
 *  Hanya salah satu parent* yang terisi untuk tiap baris.
 */
export const mediaItems = sqliteTable(
	"media_items",
	{
		id: integer("id").primaryKey({ autoIncrement: true }),
		parentType: text("parent_type").$type<MediaParentType>().notNull(), // "MOVIE" | "EPISODE"
		movieId: text("movie_id").references(() => movies.id, {
			onDelete: "cascade",
		}),
		episodeId: text("episode_id").references(() => episodes.id, {
			onDelete: "cascade",
		}),

		path: text("path").notNull(), // absolute/virtual path
		etag: text("etag"), // hash/signature untuk deteksi perubahan
		sizeBytes: integer("size_bytes"),
		container: text("container"), // mkv/mp4/…

		createdAt: integer("created_at", { mode: "timestamp" })
			.$defaultFn(() => new Date())
			.notNull(),
		updatedAt: integer("updated_at", { mode: "timestamp" })
			.$defaultFn(() => new Date())
			.$onUpdate(() => new Date())
			.notNull(),
	},
	(t) => [
		uniqueIndex("ux_media_items_path").on(t.path),
		index("idx_media_items_parent_movie").on(t.parentType, t.movieId),
		index("idx_media_items_parent_episode").on(t.parentType, t.episodeId),
	],
);

/**
 * media_streams = hasil parse per-stream dari ffprobe:
 *  - satu baris per stream (video/audio/subtitle/dll)
 */
export const mediaStreams = sqliteTable(
	"media_streams",
	{
		id: integer("id").primaryKey({ autoIncrement: true }),
		mediaItemId: integer("media_item_id")
			.notNull()
			.references(() => mediaItems.id, { onDelete: "cascade" }),

		// metadata utama (umum)
		streamIndex: integer("stream_index").notNull(), // index stream di container
		codecType: text("codec_type").$type<StreamCodecType>().notNull(), // "VIDEO" | "AUDIO" | "SUBTITLE" | ...
		codecName: text("codec_name"),
		codecLongName: text("codec_long_name"),
		profile: text("profile"),
		bitRate: integer("bit_rate"),

		// video fields
		width: integer("width"),
		height: integer("height"),
		frameRate: real("frame_rate"), // fps
		// audio fields
		channels: integer("channels"),
		channelLayout: text("channel_layout"),
		sampleRate: integer("sample_rate"),

		// subtitle / common
		language: text("language"), // "ID" | "EN" | ...
		title: text("title"),
		isDefault: integer("is_default", { mode: "boolean" })
			.notNull()
			.default(false),
		isForced: integer("is_forced", { mode: "boolean" })
			.notNull()
			.default(false),

		// simpan potongan JSON stream mentah (opsional)
		streamJson: text("stream_json"),
	},
	(t) => [
		uniqueIndex("ux_stream_media_idx").on(t.mediaItemId, t.streamIndex),
		index("idx_stream_media").on(t.mediaItemId),
		index("idx_stream_codec_type").on(t.codecType),
	],
);
