import { pgTable, serial, text, boolean, timestamp, integer, jsonb } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';

export const users = pgTable('User', {
  id: serial('id').primaryKey(),
  telegramId: text('telegramId').unique().notNull(),
  username: text('username'),
  firstName: text('firstName'),
  isPremium: boolean('isPremium').default(false),
  createdAt: timestamp('createdAt').defaultNow(),
});

export const tests = pgTable('Test', {
  id: serial('id').primaryKey(),
  userId: integer('userId').references(() => users.id).notNull(),
  answers: jsonb('answers').notNull(),
  currentStep: integer('currentStep').default(0).notNull(),
  completedAt: timestamp('completedAt'),
  result: text('result'),
  createdAt: timestamp('createdAt').defaultNow(),
});

export const payments = pgTable('Payment', {
  id: serial('id').primaryKey(),
  userId: integer('userId').references(() => users.id).notNull(),
  type: text('type').notNull(),
  amount: integer('amount').notNull(),
  currency: text('currency').notNull(),
  orderId: text('orderId').unique().notNull(),
  paymentUrl: text('paymentUrl'),
  status: text('status').default('pending'),
  paymentId: text('paymentId'),
  createdAt: timestamp('createdAt').defaultNow(),
});

export const usersRelations = relations(users, ({ many }) => ({
  tests: many(tests),
  payments: many(payments),
}));

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

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