import { db } from '../db/db_index'
import { homeBanners } from '../db/schema'
import { asc, isNotNull } from 'drizzle-orm'
import type { InferSelectModel } from 'drizzle-orm'
import type { UserBanner } from '@packages/shared'

type BannerRow = InferSelectModel<typeof homeBanners>

const mapBanner = (banner: BannerRow): UserBanner => ({
  id: banner.id,
  name: banner.name,
  imageUrl: banner.imageUrl,
  description: banner.description ?? null,
  productIds: banner.productIds ?? null,
  redirectUrl: banner.redirectUrl ?? null,
  serialNum: banner.serialNum ?? null,
  isActive: banner.isActive,
  createdAt: banner.createdAt,
  lastUpdated: banner.lastUpdated,
})

export async function getActiveBanners(): Promise<UserBanner[]> {
  const banners = await db.query.homeBanners.findMany({
    where: isNotNull(homeBanners.serialNum),
    orderBy: asc(homeBanners.serialNum),
  })

  return banners.map(mapBanner)
}
