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

// --- TYPES ---
export type ModerationCase = InferSelectModel<typeof moderationCases>;
export type Lootdrop = InferSelectModel<typeof lootdrops>;

// --- TABLES ---
export const moderationCases = pgTable('moderation_cases', {
    id: bigserial('id', { mode: 'bigint' }).primaryKey(),
    caseId: varchar('case_id', { length: 50 }).unique().notNull(),
    type: varchar('type', { length: 20 }).notNull(), // 'warn', 'timeout', 'kick', 'ban', 'note', 'prune'
    userId: bigint('user_id', { mode: 'bigint' }).notNull(),
    username: varchar('username', { length: 255 }).notNull(),
    moderatorId: bigint('moderator_id', { mode: 'bigint' }).notNull(),
    moderatorName: varchar('moderator_name', { length: 255 }).notNull(),
    reason: text('reason').notNull(),
    metadata: jsonb('metadata').default({}),
    active: boolean('active').default(true).notNull(),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
    resolvedAt: timestamp('resolved_at', { withTimezone: true }),
    resolvedBy: bigint('resolved_by', { mode: 'bigint' }),
    resolvedReason: text('resolved_reason'),
}, (table) => [
    index('moderation_cases_user_id_idx').on(table.userId),
    index('moderation_cases_case_id_idx').on(table.caseId),
]);

export const lootdrops = pgTable('lootdrops', {
    messageId: varchar('message_id', { length: 255 }).primaryKey(),
    channelId: varchar('channel_id', { length: 255 }).notNull(),
    rewardAmount: integer('reward_amount').notNull(),
    currency: varchar('currency', { length: 50 }).notNull(),
    claimedBy: bigint('claimed_by', { mode: 'bigint' }).references(() => users.id, { onDelete: 'set null' }),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
    expiresAt: timestamp('expires_at', { withTimezone: true }),
});

// --- RELATIONS ---
export const moderationCasesRelations = relations(moderationCases, ({ one }) => ({
    user: one(users, {
        fields: [moderationCases.userId],
        references: [users.id],
    }),
    moderator: one(users, {
        fields: [moderationCases.moderatorId],
        references: [users.id],
    }),
    resolver: one(users, {
        fields: [moderationCases.resolvedBy],
        references: [users.id],
    }),
}));
