import { Context } from 'hono';
import { scaffoldAssetUrl } from "@/src/lib/s3-client"
import { getNextDeliveryDate } from "@/src/trpc/apis/common-apis/common"
import {
  getAllProductsWithUnits,
  type ProductSummaryData,
} from "@/src/dbService"

/**
 * Get all products summary for dropdown
 */
export const getAllProductsSummary = async (c: Context) => {
  try {
    const tagId = c.req.query('tagId');
    const tagIdNum = tagId ? parseInt(tagId) : undefined;

    // If tagId is provided but no products found, return empty array
    if (tagIdNum) {
      const products = await getAllProductsWithUnits(tagIdNum);
      if (products.length === 0) {
        return c.json({
          products: [],
          count: 0,
        }, 200);
      }
    }

    const productsWithUnits = await getAllProductsWithUnits(tagIdNum);

    // Generate signed URLs for product images
    const formattedProducts = await Promise.all(
      productsWithUnits.map(async (product: ProductSummaryData) => {
        const nextDeliveryDate = await getNextDeliveryDate(product.id);
        return {
          id: product.id,
          name: product.name,
          shortDescription: product.shortDescription,
          price: product.price,
          marketPrice: product.marketPrice,
          unit: product.unitShortNotation,
          productQuantity: product.productQuantity,
          isOutOfStock: product.isOutOfStock,
          nextDeliveryDate: nextDeliveryDate ? nextDeliveryDate.toISOString() : null,
          images: scaffoldAssetUrl((product.images as string[]) || []),
        };
      })
    );

    return c.json({
      products: formattedProducts,
      count: formattedProducts.length,
    }, 200);
  } catch (error) {
    console.error("Get products summary error:", error);
    return c.json({ error: "Failed to fetch products summary" }, 500);
  }
};

/*
// Old implementation - direct DB queries:
import { eq, gt, and, sql, inArray } from "drizzle-orm";
import { db } from "@/src/db/db_index"
import { productInfo, units, productSlots, deliverySlotInfo, productTags } from "@/src/db/schema"

const getNextDeliveryDate = async (productId: number): Promise<Date | null> => {
  const result = await db
    .select({ deliveryTime: deliverySlotInfo.deliveryTime })
    .from(productSlots)
    .innerJoin(deliverySlotInfo, eq(productSlots.slotId, deliverySlotInfo.id))
    .where(
      and(
        eq(productSlots.productId, productId),
        eq(deliverySlotInfo.isActive, true),
        gt(deliverySlotInfo.deliveryTime, sql`NOW()`)
      )
    )
    .orderBy(deliverySlotInfo.deliveryTime)
    .limit(1);
  
  return result[0]?.deliveryTime || null;
};

export const getAllProductsSummary = async (req: Request, res: Response) => {
  try {
    const { tagId } = req.query;
    const tagIdNum = tagId ? parseInt(tagId as string) : null;

    let productIds: number[] | null = null;

    // If tagId is provided, get products that have this tag
    if (tagIdNum) {
      const taggedProducts = await db
        .select({ productId: productTags.productId })
        .from(productTags)
        .where(eq(productTags.tagId, tagIdNum));

      productIds = taggedProducts.map(tp => tp.productId);
    }

    let whereCondition = undefined;

    // Filter by product IDs if tag filtering is applied
    if (productIds && productIds.length > 0) {
      whereCondition = inArray(productInfo.id, productIds);
    } else if (tagIdNum) {
      // If tagId was provided but no products found, return empty array
      return res.status(200).json({
        products: [],
        count: 0,
      });
    }

    const productsWithUnits = await db
      .select({
        id: productInfo.id,
        name: productInfo.name,
        shortDescription: productInfo.shortDescription,
        price: productInfo.price,
        marketPrice: productInfo.marketPrice,
        images: productInfo.images,
        isOutOfStock: productInfo.isOutOfStock,
        unitShortNotation: units.shortNotation,
        productQuantity: productInfo.productQuantity,
      })
      .from(productInfo)
      .innerJoin(units, eq(productInfo.unitId, units.id))
      .where(whereCondition);

    // Generate signed URLs for product images
    const formattedProducts = await Promise.all(
      productsWithUnits.map(async (product) => {
        const nextDeliveryDate = await getNextDeliveryDate(product.id);
        return {
          id: product.id,
          name: product.name,
          shortDescription: product.shortDescription,
          price: product.price,
          marketPrice: product.marketPrice,
          unit: product.unitShortNotation,
          productQuantity: product.productQuantity,
          isOutOfStock: product.isOutOfStock,
          nextDeliveryDate: nextDeliveryDate ? nextDeliveryDate.toISOString() : null,
          images: scaffoldAssetUrl((product.images as string[]) || []),
        };
      })
    );

    return res.status(200).json({
      products: formattedProducts,
      count: formattedProducts.length,
    });
  } catch (error) {
    console.error("Get products summary error:", error);
    return res.status(500).json({ error: "Failed to fetch products summary" });
  }
};
*/
