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

export const bannerRouter = router({
  getBanners: publicProcedure
    .query(async () => {
      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 = await Promise.all(
        banners.map(async (banner) => {
          try {
            return {
              ...banner,
              imageUrl: banner.imageUrl ? await generateSignedUrlFromS3Url(banner.imageUrl) : banner.imageUrl,
            };
          } catch (error) {
            console.error(`Failed to generate signed URL for banner ${banner.id}:`, error);
            return {
              ...banner,
              imageUrl: banner.imageUrl, // Keep original on error
            };
          }
        })
      );

      console.log({bannersWithSignedUrls})
      
      
      return {
        banners: bannersWithSignedUrls,
      };
    }),
});