import { db } from '@/src/db/db_index';
import { homeBanners } from '@/src/db/schema';
import { publicProcedure, router } from '@/src/trpc/trpc-index';
import { scaffoldAssetUrl } from '@/src/lib/s3-client';
import { isNotNull, asc } from 'drizzle-orm';

export async function scaffoldBanners() {
  const banners = await db.query.homeBanners.findMany({
    where: isNotNull(homeBanners.serialNum), // Only show assigned banners
    orderBy: asc(homeBanners.serialNum), // Order by slot number 1-4
  });

  // Convert S3 keys to signed URLs for client
  const bannersWithSignedUrls = banners.map((banner) => ({
    ...banner,
    imageUrl: banner.imageUrl ? scaffoldAssetUrl(banner.imageUrl) : banner.imageUrl,
  }));

  return {
    banners: bannersWithSignedUrls,
  };
}

export const bannerRouter = router({
  getBanners: publicProcedure
    .query(async () => {
      const response = await scaffoldBanners();
      return response;
    }),
});
