import { eq, and, count, type Column } from 'drizzle-orm'
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import { discounts } from '../db/schema/pos.js'
import type { DiscountCreateInput, DiscountUpdateInput, PaginationInput } from '@lunarfront/shared/schemas'
import { withPagination, withSort, buildSearchCondition, paginatedResponse } from '../utils/pagination.js'

export const DiscountService = {
  async create(db: PostgresJsDatabase<any>, input: DiscountCreateInput) {
    const [discount] = await db
      .insert(discounts)
      .values({
        ...input,
        discountValue: input.discountValue.toString(),
        requiresApprovalAbove: input.requiresApprovalAbove?.toString(),
        validFrom: input.validFrom ? new Date(input.validFrom) : undefined,
        validUntil: input.validUntil ? new Date(input.validUntil) : undefined,
      })
      .returning()
    return discount
  },

  async getById(db: PostgresJsDatabase<any>, id: string) {
    const [discount] = await db
      .select()
      .from(discounts)
      .where(eq(discounts.id, id))
      .limit(1)
    return discount ?? null
  },

  async list(db: PostgresJsDatabase<any>, params: PaginationInput) {
    const conditions = [eq(discounts.isActive, true)]

    if (params.q) {
      conditions.push(buildSearchCondition(params.q, [discounts.name])!)
    }

    const where = conditions.length === 1 ? conditions[0] : and(...conditions)

    const sortableColumns: Record<string, Column> = {
      name: discounts.name,
      discount_type: discounts.discountType,
      created_at: discounts.createdAt,
    }

    let query = db.select().from(discounts).where(where).$dynamic()
    query = withSort(query, params.sort, params.order, sortableColumns, discounts.name)
    query = withPagination(query, params.page, params.limit)

    const [data, [{ total }]] = await Promise.all([
      query,
      db.select({ total: count() }).from(discounts).where(where),
    ])

    return paginatedResponse(data, total, params.page, params.limit)
  },

  async listAll(db: PostgresJsDatabase<any>) {
    return db
      .select()
      .from(discounts)
      .where(eq(discounts.isActive, true))
      .orderBy(discounts.name)
  },

  async update(db: PostgresJsDatabase<any>, id: string, input: DiscountUpdateInput) {
    const updates: Record<string, unknown> = { ...input, updatedAt: new Date() }
    if (input.discountValue !== undefined) updates.discountValue = input.discountValue.toString()
    if (input.requiresApprovalAbove !== undefined) updates.requiresApprovalAbove = input.requiresApprovalAbove.toString()
    if (input.validFrom !== undefined) updates.validFrom = input.validFrom ? new Date(input.validFrom) : null
    if (input.validUntil !== undefined) updates.validUntil = input.validUntil ? new Date(input.validUntil) : null

    const [discount] = await db
      .update(discounts)
      .set(updates)
      .where(eq(discounts.id, id))
      .returning()
    return discount ?? null
  },

  async softDelete(db: PostgresJsDatabase<any>, id: string) {
    const [discount] = await db
      .update(discounts)
      .set({ isActive: false, updatedAt: new Date() })
      .where(eq(discounts.id, id))
      .returning()
    return discount ?? null
  },
}
