import { router, publicProcedure } from '@/src/trpc/trpc-index'
import {
  getSuspendedProductIds,
  getNextDeliveryDateWithCapacity,
  getStoresSummary,
} from '@/src/dbService'
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url } from '@/src/lib/s3-client'
import { getAllProducts as getAllProductsFromCache } from '@/src/stores/product-store'
import { getDashboardTags as getDashboardTagsFromCache } from '@/src/stores/product-tag-store'

// Re-export with original name for backwards compatibility
export const getNextDeliveryDate = getNextDeliveryDateWithCapacity

export async function scaffoldProducts() {
  // Get all products from cache
  let products = await getAllProductsFromCache();
  products = products.filter(item => Boolean(item.id))

  /*
  // Old implementation - direct DB queries:
  import { db } from '@/src/db/db_index'
  import { productInfo } from '@/src/db/schema'
  import { eq } from 'drizzle-orm';

  // Get suspended product IDs to filter them out
  const suspendedProducts = await db
    .select({ id: productInfo.id })
    .from(productInfo)
    .where(eq(productInfo.isSuspended, true));
  */

  const suspendedProductIds = new Set(await getSuspendedProductIds());

  // Filter out suspended products
  products = products.filter(product => !suspendedProductIds.has(product.id));

  // Format products to match the expected response structure
  const formattedProducts = await Promise.all(
    products.map(async (product) => {
      const nextDeliveryDate = await getNextDeliveryDateWithCapacity(product.id);
      return {
        id: product.id,
        name: product.name,
        shortDescription: product.shortDescription,
        price: parseFloat(product.price),
        marketPrice: product.marketPrice ? parseFloat(product.marketPrice) : null,
        unit: product.unitNotation,
        unitNotation: product.unitNotation,
        incrementStep: product.incrementStep,
        productQuantity: product.productQuantity,
        storeId: product.store?.id || null,
        isOutOfStock: product.isOutOfStock,
        isFlashAvailable: product.isFlashAvailable,
        nextDeliveryDate: nextDeliveryDate ? nextDeliveryDate.toISOString() : null,
        images: product.images,
        flashPrice: product.flashPrice
      };
    })
  );

  return {
    products: formattedProducts,
    count: formattedProducts.length,
  };
}

export const commonRouter = router({
  getDashboardTags: publicProcedure
    .query(async () => {
      // Get dashboard tags from cache
      const tags = await getDashboardTagsFromCache();

      return {
        tags: tags,
      };
    }),

  getAllProductsSummary: publicProcedure
    .query(async () => {
      const response = await scaffoldProducts();
      return response;
    }),

  /*
  // Old implementation - moved to common-trpc-index.ts:
  getStoresSummary: publicProcedure
    .query(async () => {
      const stores = await getStoresSummary();
      return { stores };
    }),

  healthCheck: publicProcedure
    .query(async () => {
      const result = await healthCheck();
      return result;
    }),
  */
});
