import { NextRequest, NextResponse } from "next/server";
import { db, mealPlans, eq, and } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { buildIcs, type IcsEvent } from "@/lib/ics";

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

const DAY_OFFSET: Record<string, number> = { mon: 0, tue: 1, wed: 2, thu: 3, fri: 4, sat: 5, sun: 6 };

// No stored time-of-day for a meal slot, so each mealType gets a
// conventional wall-clock time and a rough duration for the calendar block.
const MEAL_TIME: Record<string, { hour: number; minute: number; durationMinutes: number }> = {
  breakfast: { hour: 8, minute: 0, durationMinutes: 30 },
  lunch: { hour: 12, minute: 30, durationMinutes: 45 },
  dinner: { hour: 19, minute: 0, durationMinutes: 60 },
  snack: { hour: 15, minute: 30, durationMinutes: 15 },
};

export async function GET(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { weekStart } = await params;

  const [y, m, d] = weekStart.split("-").map(Number);
  if (!y || !m || !d) return NextResponse.json({ error: "Invalid weekStart" }, { status: 400 });
  const monday = new Date(y, m - 1, d);

  const plan = await db.query.mealPlans.findFirst({
    where: and(eq(mealPlans.userId, session!.user.id), eq(mealPlans.weekStart, weekStart)),
    with: { entries: { with: { recipe: true, batchDish: true } } },
  });

  const events: IcsEvent[] = (plan?.entries ?? []).flatMap((entry) => {
    const title = entry.batchDish?.name ?? entry.recipe?.title;
    if (!title) return [];
    const offset = DAY_OFFSET[entry.day] ?? 0;
    const time = MEAL_TIME[entry.mealType] ?? MEAL_TIME["dinner"]!;
    const start = new Date(monday);
    start.setDate(start.getDate() + offset);
    start.setHours(time.hour, time.minute, 0, 0);

    return [{
      uid: `epicure-meal-${entry.id}@epicure`,
      title: `${title} (${entry.mealType})`,
      description: entry.note ?? undefined,
      start,
      durationMinutes: time.durationMinutes,
    }];
  });

  const ics = buildIcs(`Epicure meal plan — week of ${weekStart}`, events);

  return new NextResponse(ics, {
    headers: {
      "Content-Type": "text/calendar; charset=utf-8",
      "Content-Disposition": `attachment; filename="meal-plan-${weekStart}.ics"`,
    },
  });
}
