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

/**
 * Alternative names for groups.
 *
 * Source: AmqGroupSchema.altNames
 *
 * The source uses objects shaped like `{ songGroupId, name }`, but that nested
 * `songGroupId` is effectively the *context group* the alias is associated with.
 * We persist it as `contextSongGroupId` to make the meaning explicit.
 */
export const groupAltNames = sqliteTable(
	"group_alt_names",
	{
		id: integer("id").notNull().primaryKey({ autoIncrement: true }),

		/**
		 * The "owning" group.
		 */
		songGroupId: integer("song_group_id")
			.notNull()
			.references(() => groups.songGroupId, { onDelete: "cascade" }),

		/**
		 * Context group the alias is associated with.
		 * (This is the nested `songGroupId` value in the source.)
		 */
		contextSongGroupId: integer("context_song_group_id")
			.notNull()
			.references(() => groups.songGroupId, { onDelete: "cascade" }),

		name: text("name").notNull(),
	},
	(t) => ({
		groupIndex: index("group_alt_names_group_id_idx").on(t.songGroupId),
		contextGroupIndex: index("group_alt_names_context_group_id_idx").on(
			t.contextSongGroupId,
		),
		nameIndex: index("group_alt_names_name_idx").on(t.name),
		uniquePerGroupContextName: uniqueIndex(
			"group_alt_names_group_context_name_uq",
		).on(t.songGroupId, t.contextSongGroupId, t.name),
	}),
);
