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

// --- TYPES ---
export type Quest = InferSelectModel<typeof quests>;
export type UserQuest = InferSelectModel<typeof userQuests>;

// --- TABLES ---
export const quests = pgTable('quests', {
    id: serial('id').primaryKey(),
    name: varchar('name', { length: 255 }).notNull(),
    description: text('description'),
    triggerEvent: varchar('trigger_event', { length: 50 }).notNull(),
    requirements: jsonb('requirements').notNull().default({}),
    rewards: jsonb('rewards').notNull().default({}),
});

export const userQuests = pgTable('user_quests', {
    userId: bigint('user_id', { mode: 'bigint' })
        .references(() => users.id, { onDelete: 'cascade' }).notNull(),
    questId: integer('quest_id')
        .references(() => quests.id, { onDelete: 'cascade' }).notNull(),
    progress: integer('progress').default(0),
    completedAt: timestamp('completed_at', { withTimezone: true }),
}, (table) => [
    primaryKey({ columns: [table.userId, table.questId] })
]);

// --- RELATIONS ---
export const questsRelations = relations(quests, ({ many }) => ({
    userEntries: many(userQuests),
}));

export const userQuestsRelations = relations(userQuests, ({ one }) => ({
    user: one(users, {
        fields: [userQuests.userId],
        references: [users.id],
    }),
    quest: one(quests, {
        fields: [userQuests.questId],
        references: [quests.id],
    }),
}));
