import {
    pgTable,
    bigint,
    varchar,
    text,
    timestamp,
    bigserial,
    index,
    integer,
} from 'drizzle-orm/pg-core';
import { relations, type InferSelectModel } from 'drizzle-orm';
import { users } from './users';
import { items } from './inventory';

// --- TYPES ---
export type Transaction = InferSelectModel<typeof transactions>;
export type ItemTransaction = InferSelectModel<typeof itemTransactions>;

// --- TABLES ---
export const transactions = pgTable('transactions', {
    id: bigserial('id', { mode: 'bigint' }).primaryKey(),
    userId: bigint('user_id', { mode: 'bigint' })
        .references(() => users.id, { onDelete: 'cascade' }),
    relatedUserId: bigint('related_user_id', { mode: 'bigint' })
        .references(() => users.id, { onDelete: 'set null' }),
    amount: bigint('amount', { mode: 'bigint' }).notNull(),
    type: varchar('type', { length: 50 }).notNull(),
    description: text('description'),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
}, (table) => [
    index('transactions_created_at_idx').on(table.createdAt),
]);

export const itemTransactions = pgTable('item_transactions', {
    id: bigserial('id', { mode: 'bigint' }).primaryKey(),
    userId: bigint('user_id', { mode: 'bigint' })
        .references(() => users.id, { onDelete: 'cascade' }).notNull(),
    relatedUserId: bigint('related_user_id', { mode: 'bigint' })
        .references(() => users.id, { onDelete: 'set null' }),
    itemId: integer('item_id')
        .references(() => items.id, { onDelete: 'cascade' }).notNull(),
    quantity: bigint('quantity', { mode: 'bigint' }).notNull(),
    type: varchar('type', { length: 50 }).notNull(), // e.g., 'TRADE', 'SHOP_BUY', 'DROP'
    description: text('description'),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
});

// --- RELATIONS ---
export const transactionsRelations = relations(transactions, ({ one }) => ({
    user: one(users, {
        fields: [transactions.userId],
        references: [users.id],
    }),
}));

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