import {
	index,
	integer,
	real,
	sqliteTable,
	text,
} from "drizzle-orm/sqlite-core";
import { artists } from "./artists";
import { groups } from "./groups";

/**
 * Core `songs` table.
 *
 * Source: AmqSongSchema
 */
export const songs = sqliteTable(
	"songs",
	{
		/** AMQ annSongId (ANN song id) */
		annSongId: integer("ann_song_id").notNull().primaryKey(),

		/** AMQ songId */
		songId: integer("song_id").notNull(),

		name: text("name").notNull(),

		/**
		 * AmqSongCategory enum from the source:
		 * none(0), instrumental(1), chanting(2), character(3), standard(4)
		 */
		category: integer("category").notNull(),

		/**
		 * Song audio filename used by the AMQ CDN:
		 * https://nawdist.animemusicquiz.com/{fileName}
		 */
		fileName: text("file_name"),
		fileName480: text("file_name_480"),
		fileName720: text("file_name_720"),
		globalPercent: integer("global_percent"),
		meanVolume: real("mean_volume"),

		/**
		 * Primary artist/group ids for this song (nullable in source).
		 * These reference existing `artists` / `groups` rows.
		 */
		songArtistId: integer("song_artist_id").references(
			() => artists.songArtistId,
			{ onDelete: "set null" },
		),
		songGroupId: integer("song_group_id").references(() => groups.songGroupId, {
			onDelete: "set null",
		}),

		/**
		 * Additional contributor ids (nullable in source)
		 */
		composerArtistId: integer("composer_artist_id").references(
			() => artists.songArtistId,
			{ onDelete: "set null" },
		),
		composerGroupId: integer("composer_group_id").references(
			() => groups.songGroupId,
			{ onDelete: "set null" },
		),
		arrangerArtistId: integer("arranger_artist_id").references(
			() => artists.songArtistId,
			{ onDelete: "set null" },
		),
		arrangerGroupId: integer("arranger_group_id").references(
			() => groups.songGroupId,
			{ onDelete: "set null" },
		),
	},
	(t) => ({
		songIdIndex: index("songs_song_id_idx").on(t.songId),
		songArtistIdIndex: index("songs_song_artist_id_idx").on(t.songArtistId),
		songGroupIdIndex: index("songs_song_group_id_idx").on(t.songGroupId),
	}),
);
