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

/**
 * Alternative names for artists.
 *
 * Source: AmqArtistSchema.altNames
 *
 * Interpreted as: artist `songArtistId` is also known as `name` (optionally via altSongArtistId link).
 */
export const artistAltNames = sqliteTable(
	"artist_alt_names",
	{
		id: integer("id").notNull().primaryKey({ autoIncrement: true }),

		/**
		 * The "owning" artist.
		 */
		songArtistId: integer("song_artist_id")
			.notNull()
			.references(() => artists.songArtistId, {
				onDelete: "cascade",
			}),

		/**
		 * The alternate-name entry is keyed by an artist id in the source:
		 * { songArtistId, name }
		 *
		 * Store as a linked artist row for referential integrity.
		 */
		altSongArtistId: integer("alt_song_artist_id")
			.notNull()
			.references(() => artists.songArtistId, {
				onDelete: "cascade",
			}),

		name: text("name").notNull(),
	},
	(t) => ({
		artistIndex: index("artist_alt_names_artist_id_idx").on(t.songArtistId),
		altArtistIndex: index("artist_alt_names_alt_artist_id_idx").on(
			t.altSongArtistId,
		),
		nameIndex: index("artist_alt_names_name_idx").on(t.name),
		uniquePerArtistAltArtistName: uniqueIndex(
			"artist_alt_names_artist_alt_artist_name_uq",
		).on(t.songArtistId, t.altSongArtistId, t.name),
	}),
);
