import { NextRequest, NextResponse } from "next/server";
import { connectDB } from "@/lib/db";
import { Order } from "@/models/Order";
import { getSessionClientId } from "@/lib/auth";
import { hasPermission } from "@/lib/adminAuth";
import { buildIcsFeed } from "@/lib/ics";
import { effectiveEventAddress } from "@/lib/orderConstants";

// Einzelner Termin als .ics zum Herunterladen — für Apple Kalender/Outlook
// Desktop/o. Ä. Google/Outlook.com haben eigene Quick-Add-Links, siehe
// lib/addToCalendarLinks.ts, direkt auf der Auftragsseite verlinkt.
export async function GET(_req: NextRequest, { params }: { params: Promise<{ orderId: string }> }) {
  const { orderId } = await params;
  const [clientId, isAdmin] = await Promise.all([getSessionClientId(), hasPermission("orders_view")]);
  if (!clientId && !isAdmin) return new NextResponse("Unauthorized", { status: 401 });

  await connectDB();
  const order = await Order.findById(orderId).lean();
  if (!order || (!isAdmin && String(order.clientId) !== clientId)) {
    return new NextResponse("Not found", { status: 404 });
  }
  if (!order.shootDate) return new NextResponse("Kein Termin gesetzt.", { status: 404 });

  const ics = buildIcsFeed("Rakku Photography", [
    {
      uid: `order-${order._id}`,
      title: `${order.characterOrConcept} — Rakku Photography`,
      description: "Shooting-Termin bei Rakku Photography.",
      location: effectiveEventAddress(order),
      start: new Date(order.shootDate),
      end: order.shootEndDate ? new Date(order.shootEndDate) : null,
    },
  ]);

  return new NextResponse(ics, {
    headers: {
      "Content-Type": "text/calendar; charset=utf-8",
      "Content-Disposition": `attachment; filename="termin-${String(order._id).slice(-8)}.ics"`,
      "Cache-Control": "private, max-age=0, no-store",
    },
  });
}
