import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { getAiDisabledMessage, isAdminAiEnabled } from "@/lib/ai-feature-flags";
import { openRouterClient } from "@/lib/openrouter-client";

export async function POST(request: Request) {
	if (!isAdminAiEnabled()) {
		return NextResponse.json(
			{ error: getAiDisabledMessage() },
			{ status: 403 },
		);
	}

	const session = await auth.api.getSession({
		headers: await headers(),
	});

	if (!session?.user) {
		return NextResponse.json(
			{ error: "Authentication required" },
			{ status: 401 },
		);
	}

	try {
		const { events } = await request.json();

		if (!events || !Array.isArray(events)) {
			return NextResponse.json(
				{ error: "Invalid events array" },
				{ status: 400 },
			);
		}
		if (events.length > 100) {
			return NextResponse.json(
				{ error: "Events array must contain 100 or fewer items" },
				{ status: 400 },
			);
		}

		const result = openRouterClient.callModel({
			model: "@preset/i-cal-editor-summarize", // FREE model
			instructions:
				"You summarize a list of events in natural language. Include date, time, and title. Be concise.",
			input: JSON.stringify(events),
			temperature: 0.4,
		});

		const summary = await result.getText();
		return NextResponse.json({ summary });
	} catch (error) {
		console.error("AI Summary Error:", error);
		return NextResponse.json(
			{ error: "Failed to summarize events" },
			{ status: 500 },
		);
	}
}
