import {
	pgTable,
	uuid,
	text,
	varchar,
	boolean,
	integer,
	timestamp,
	index,
} from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';

export const albums = pgTable(
	'albums',
	{
		id: uuid('id').primaryKey().defaultRandom(),
		userId: text('user_id').notNull(),
		name: varchar('name', { length: 255 }).notNull(),
		description: text('description'),
		coverMediaId: text('cover_media_id'),
		isAutoGenerated: boolean('is_auto_generated').default(false).notNull(),
		autoGenerateType: text('auto_generate_type'),
		autoGenerateValue: text('auto_generate_value'),
		sortOrder: integer('sort_order').default(0).notNull(),
		createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
		updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
	},
	(table) => [index('albums_user_id_idx').on(table.userId)]
);

export const albumItems = pgTable(
	'album_items',
	{
		id: uuid('id').primaryKey().defaultRandom(),
		albumId: uuid('album_id')
			.references(() => albums.id, { onDelete: 'cascade' })
			.notNull(),
		mediaId: text('media_id').notNull(),
		sortOrder: integer('sort_order').default(0).notNull(),
		addedAt: timestamp('added_at', { withTimezone: true }).defaultNow().notNull(),
	},
	(table) => [
		index('album_items_album_id_idx').on(table.albumId),
		index('album_items_media_id_idx').on(table.mediaId),
	]
);

export const albumsRelations = relations(albums, ({ many }) => ({
	items: many(albumItems),
}));

export const albumItemsRelations = relations(albumItems, ({ one }) => ({
	album: one(albums, {
		fields: [albumItems.albumId],
		references: [albums.id],
	}),
}));

export type Album = typeof albums.$inferSelect;
export type NewAlbum = typeof albums.$inferInsert;
export type AlbumItem = typeof albumItems.$inferSelect;
export type NewAlbumItem = typeof albumItems.$inferInsert;
