import { and, eq, isNull } from 'drizzle-orm'
import type { Querier } from '@platform-modules/db'
import { promo, type PromotionsSchema } from './schema.js'
import type { Promo, PromoEligibility, PromoFunder, PromoKind, PromoScope } from './types.js'

function rowToPromo(row: typeof promo.$inferSelect): Promo {
  const kind = row.kind as PromoKind
  const result: Promo = {
    id: row.id,
    code: row.code,
    kind,
    scope: row.scope as PromoScope,
    eligibility: row.eligibility as PromoEligibility,
    funder: row.funder as PromoFunder,
    active: row.active,
    vendorId: row.vendorId ?? null,
  }

  if (row.valueBps != null) {
    result.valueBps = row.valueBps
  }
  if (row.valueAmount != null) {
    result.valueAmount = row.valueAmount
  }
  if (row.currency != null) {
    result.currency = row.currency
  }
  if (row.maxDiscountAmount != null) {
    result.maxDiscountAmount = row.maxDiscountAmount
  }
  if (kind === 'bogo' && row.bogoBuyQty != null && row.bogoGetQty != null) {
    result.bogo = { buyQty: row.bogoBuyQty, getQty: row.bogoGetQty }
  }
  if (row.maxUses != null) {
    result.maxUses = row.maxUses
  }
  if (row.perUserCap != null) {
    result.perUserCap = row.perUserCap
  }
  if (row.startsAt != null) {
    result.startsAt = row.startsAt
  }
  if (row.endsAt != null) {
    result.endsAt = row.endsAt
  }
  if (row.minOrderAmount != null) {
    result.minOrderAmount = row.minOrderAmount
  }
  if (row.maxOrderAmount != null) {
    result.maxOrderAmount = row.maxOrderAmount
  }

  return result
}

export async function getPromoByCode(
  q: Querier<PromotionsSchema>,
  code: string,
  vendorId?: string | null,
): Promise<Promo | null> {
  const where =
    vendorId != null && vendorId !== undefined
      ? and(eq(promo.code, code), eq(promo.vendorId, vendorId))
      : and(eq(promo.code, code), isNull(promo.vendorId))

  const [row] = await q.select().from(promo).where(where).limit(1)
  if (!row) {
    return null
  }

  return rowToPromo(row)
}
