import { db } from '../db/db_index'
import { deliverySlotInfo, productInfo } from '../db/schema'
import { asc, eq } from 'drizzle-orm'
import type { InferSelectModel } from 'drizzle-orm'
import type { UserDeliverySlot, UserSlotAvailability } from '@packages/shared'

type SlotRow = InferSelectModel<typeof deliverySlotInfo>

const mapSlot = (slot: SlotRow): UserDeliverySlot => ({
  id: slot.id,
  deliveryTime: slot.deliveryTime!,
  freezeTime: slot.freezeTime!,
  isActive: slot.isActive,
  isFlash: slot.isFlash,
  isCapacityFull: slot.isCapacityFull,
  deliverySequence: slot.deliverySequence,
  groupIds: slot.groupIds,
})

export async function getActiveSlotsList(): Promise<UserDeliverySlot[]> {
  const slots = await db.query.deliverySlotInfo.findMany({
    where: eq(deliverySlotInfo.isActive, true),
    orderBy: asc(deliverySlotInfo.deliveryTime),
  })

  return slots.map(mapSlot)
}

export async function getProductAvailability(): Promise<UserSlotAvailability[]> {
  const products = await db
    .select({
      id: productInfo.id,
      name: productInfo.name,
      isOutOfStock: productInfo.isOutOfStock,
      isFlashAvailable: productInfo.isFlashAvailable,
    })
    .from(productInfo)
    .where(eq(productInfo.isSuspended, false))

  return products.map((product) => ({
    id: product.id,
    name: product.name,
    isOutOfStock: product.isOutOfStock,
    isFlashAvailable: product.isFlashAvailable,
  }))
}
