import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, cookingHistory, pantryItems, recipeIngredients, recipeBatchDishes, eq, and, desc, isNull } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { loadIngredientAliasIndex, resolveIngredientKey } from "@/lib/ingredient-match";

type Params = { params: Promise<{ id: string }> };

// Plain (non-batch) cook log entries only — batch-cook dishes have their
// own per-dish "cooked" indicator (dishCookedAtMap in the recipe page) and
// aren't meant to be edited/removed one at a time here.
export async function GET(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { id } = await params;

  const logs = await db.query.cookingHistory.findMany({
    where: and(eq(cookingHistory.recipeId, id), eq(cookingHistory.userId, session!.user.id), isNull(cookingHistory.batchDishId)),
    orderBy: desc(cookingHistory.cookedAt),
    columns: { id: true, cookedAt: true, servings: true, notes: true },
  });

  return NextResponse.json({ data: logs });
}

const Schema = z.object({
  servings: z.number().int().min(1).max(1000).optional(),
  notes: z.string().max(2000).optional(),
  deductFromPantry: z.boolean().default(true),
  batchDishId: z.string().optional(),
  /** ISO date (YYYY-MM-DD) or full datetime — lets a user log a past cook,
   * not just "just now". Defaults to now when omitted. */
  cookedAt: z.string().optional(),
});

export async function POST(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { id } = await params;
  const userId = session!.user.id;

  const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
  if (!recipe || (recipe.visibility === "private" && recipe.authorId !== userId)) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  const body = await req.json().catch(() => ({})) as unknown;
  const parsed = Schema.safeParse(body);
  const data = parsed.success ? parsed.data : { deductFromPantry: true };

  // Ingredients aren't attributable to individual batch dishes — they're one
  // merged/shared list for the whole prep session (unlike steps, which have
  // `appliesTo`). So pantry deduction for a batch-cook recipe happens once,
  // on the first dish marked cooked, rather than per-dish.
  let isFirstBatchCook = false;
  if (data.batchDishId) {
    const dish = await db.query.recipeBatchDishes.findFirst({
      where: and(eq(recipeBatchDishes.id, data.batchDishId), eq(recipeBatchDishes.recipeId, id)),
    });
    if (!dish) return NextResponse.json({ error: "Dish not found" }, { status: 404 });

    const priorCook = await db.query.cookingHistory.findFirst({
      where: and(eq(cookingHistory.recipeId, id), eq(cookingHistory.userId, userId)),
    });
    isFirstBatchCook = !priorCook;
  }

  const cookedAt = data.cookedAt ? new Date(data.cookedAt) : new Date();
  const logId = crypto.randomUUID();

  await db.insert(cookingHistory).values({
    id: logId,
    userId,
    recipeId: id,
    batchDishId: data.batchDishId,
    servings: data.servings,
    notes: data.notes,
    cookedAt: isNaN(cookedAt.getTime()) ? new Date() : cookedAt,
  });

  if (data.deductFromPantry && (!data.batchDishId || isFirstBatchCook)) {
    const ings = await db.query.recipeIngredients.findMany({
      where: eq(recipeIngredients.recipeId, id),
    });
    // A batch session's merged ingredient list is deducted once as a whole,
    // regardless of which single dish triggered the first cook — never
    // scaled by that one dish's serving count.
    const scale = data.batchDishId ? 1 : (data.servings ? data.servings / recipe.baseServings : 1);
    const userPantry = await db.query.pantryItems.findMany({
      where: eq(pantryItems.userId, userId),
    });
    const aliasIndex = await loadIngredientAliasIndex();

    for (const ing of ings) {
      const key = resolveIngredientKey(ing.rawName, aliasIndex);
      const pantryItem = userPantry.find(
        (p) => resolveIngredientKey(p.rawName, aliasIndex) === key && (p.unit ?? "") === (ing.unit ?? "")
      );
      if (!pantryItem) continue;

      const pantryQty = pantryItem.quantity ? parseFloat(pantryItem.quantity) : null;
      const ingQty = ing.quantity ? parseFloat(ing.quantity) * scale : null;

      if (pantryQty !== null && ingQty !== null && !isNaN(pantryQty) && !isNaN(ingQty)) {
        const remaining = pantryQty - ingQty;
        if (remaining <= 0) {
          await db.delete(pantryItems).where(eq(pantryItems.id, pantryItem.id));
        } else {
          await db.update(pantryItems)
            .set({ quantity: String(Math.round(remaining * 10000) / 10000) })
            .where(eq(pantryItems.id, pantryItem.id));
        }
      } else {
        // no numeric quantity to deduct — remove the item entirely
        await db.delete(pantryItems).where(eq(pantryItems.id, pantryItem.id));
      }
    }
  }

  return NextResponse.json({ logged: true, id: logId }, { status: 201 });
}
