import {
  bigint,
  boolean,
  integer,
  jsonb,
  pgTable,
  primaryKey,
  text,
  timestamp,
  uuid,
} from 'drizzle-orm/pg-core'
import type { PromoEligibility, PromoFunder, PromoKind, PromoScope } from './types.js'

export const promo = pgTable('promo', {
  id: uuid('id').primaryKey().defaultRandom(),
  code: text('code').notNull(),
  kind: text('kind').$type<PromoKind>().notNull(),
  valueBps: integer('value_bps'),
  valueAmount: bigint('value_amount', { mode: 'bigint' }),
  currency: text('currency'),
  maxDiscountAmount: bigint('max_discount_amount', { mode: 'bigint' }),
  bogoBuyQty: integer('bogo_buy_qty'),
  bogoGetQty: integer('bogo_get_qty'),
  scope: jsonb('scope').$type<PromoScope>().notNull(),
  eligibility: jsonb('eligibility').$type<PromoEligibility>().notNull(),
  funder: text('funder').$type<PromoFunder>().notNull(),
  maxUses: integer('max_uses'),
  perUserCap: integer('per_user_cap'),
  uses: integer('uses').notNull().default(0),
  startsAt: timestamp('starts_at', { withTimezone: true }),
  endsAt: timestamp('ends_at', { withTimezone: true }),
  minOrderAmount: bigint('min_order_amount', { mode: 'bigint' }),
  maxOrderAmount: bigint('max_order_amount', { mode: 'bigint' }),
  active: boolean('active').notNull().default(true),
  vendorId: text('vendor_id'),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
})

export const promoUserUsage = pgTable(
  'promo_user_usage',
  {
    promoId: uuid('promo_id').notNull(),
    userId: text('user_id').notNull(),
    uses: integer('uses').notNull().default(0),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => [primaryKey({ columns: [t.promoId, t.userId] })],
)

export const promotionsSchema = {
  promo,
  promoUserUsage,
}

export type PromotionsSchema = typeof promotionsSchema
