import {
    pgTable,
    bigint,
    varchar,
    serial,
    text,
    integer,
    jsonb,
    primaryKey,
    check,
} from 'drizzle-orm/pg-core';
import { relations, sql, type InferSelectModel } from 'drizzle-orm';
import { users } from './users';

// --- TYPES ---
export type Item = InferSelectModel<typeof items>;
export type Inventory = InferSelectModel<typeof inventory>;

// --- TABLES ---
export const items = pgTable('items', {
    id: serial('id').primaryKey(),
    name: varchar('name', { length: 255 }).unique().notNull(),
    description: text('description'),
    rarity: varchar('rarity', { length: 20 }).default('C'),
    type: varchar('type', { length: 50 }).notNull().default('MATERIAL'),
    usageData: jsonb('usage_data').default({}),
    price: bigint('price', { mode: 'bigint' }),
    iconUrl: text('icon_url').notNull(),
    imageUrl: text('image_url').notNull(),
});

export const inventory = pgTable('inventory', {
    userId: bigint('user_id', { mode: 'bigint' })
        .references(() => users.id, { onDelete: 'cascade' }).notNull(),
    itemId: integer('item_id')
        .references(() => items.id, { onDelete: 'cascade' }).notNull(),
    quantity: bigint('quantity', { mode: 'bigint' }).default(1n),
}, (table) => [
    primaryKey({ columns: [table.userId, table.itemId] }),
    check('quantity_check', sql`${table.quantity} > 0`)
]);

// --- RELATIONS ---
export const itemsRelations = relations(items, ({ many }) => ({
    inventoryEntries: many(inventory),
}));

export const inventoryRelations = relations(inventory, ({ one }) => ({
    user: one(users, {
        fields: [inventory.userId],
        references: [users.id],
    }),
    item: one(items, {
        fields: [inventory.itemId],
        references: [items.id],
    }),
}));
