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

// --- TYPES ---
export type Class = InferSelectModel<typeof classes>;
export type User = InferSelectModel<typeof users>;
export type UserTimer = InferSelectModel<typeof userTimers>;

// --- TABLES ---
export const classes = pgTable('classes', {
    id: bigint('id', { mode: 'bigint' }).primaryKey(),
    name: varchar('name', { length: 255 }).unique().notNull(),
    balance: bigint('balance', { mode: 'bigint' }).default(0n),
    roleId: varchar('role_id', { length: 255 }),
});

export const users = pgTable('users', {
    id: bigint('id', { mode: 'bigint' }).primaryKey(),
    classId: bigint('class_id', { mode: 'bigint' }).references(() => classes.id),
    username: varchar('username', { length: 255 }).unique().notNull(),
    isActive: boolean('is_active').default(true),

    // Economy
    balance: bigint('balance', { mode: 'bigint' }).default(0n),
    xp: bigint('xp', { mode: 'bigint' }).default(0n),
    level: integer('level').default(1),
    dailyStreak: integer('daily_streak').default(0),

    // Metadata
    settings: jsonb('settings').default({}),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow(),
}, (table) => [
    index('users_username_idx').on(table.username),
    index('users_balance_idx').on(table.balance),
    index('users_level_xp_idx').on(table.level, table.xp),
]);

export const userTimers = pgTable('user_timers', {
    userId: bigint('user_id', { mode: 'bigint' })
        .references(() => users.id, { onDelete: 'cascade' }).notNull(),
    type: varchar('type', { length: 50 }).notNull(), // 'COOLDOWN', 'EFFECT', 'ACCESS'
    key: varchar('key', { length: 100 }).notNull(),  // TimerKey, 'chn_12345', 'xp_boost'
    expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
    metadata: jsonb('metadata').default({}),
}, (table) => [
    primaryKey({ columns: [table.userId, table.type, table.key] }),
    index('user_timers_expires_at_idx').on(table.expiresAt),
    index('user_timers_lookup_idx').on(table.userId, table.type, table.key),
]);

// --- RELATIONS ---
export const classesRelations = relations(classes, ({ many }) => ({
    users: many(users),
}));

export const usersRelations = relations(users, ({ one, many }) => ({
    class: one(classes, {
        fields: [users.classId],
        references: [classes.id],
    }),
    timers: many(userTimers),
}));

export const userTimersRelations = relations(userTimers, ({ one }) => ({
    user: one(users, {
        fields: [userTimers.userId],
        references: [users.id],
    }),
}));
