import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { readFile } from "fs/promises";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { deleteTodoAttachmentAction } from "@/lib/actions/todos";
import { connectDB } from "@/lib/db";
import { Todo } from "@/models/Todo";
import { todoUploadPath } from "@/lib/uploads";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

// Pendant zu /api/files/todos/[todoId]/[filename] (Web-Serving-Route),
// zusätzlich mit CORS-Headern — die App liest die Bytes per fetch() aus,
// um sie danach über window.rakku.openFile() lokal zu öffnen (analog zu
// PDFs/CSV-Exports), statt direkt zu verlinken.
export async function GET(request: NextRequest, { params }: { params: Promise<{ todoId: string; storedName: string }> }) {
  const headers = corsHeaders(request);
  const viewerId = await getSessionClientId();
  if (!viewerId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { todoId, storedName } = await params;

  await connectDB();
  const todo = await Todo.findById(todoId)
    .select("attachments assignedToId additionalAssigneeIds watcherIds createdById")
    .lean();
  if (!todo) return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });

  const participants = [
    String(todo.assignedToId),
    String(todo.createdById),
    ...(todo.additionalAssigneeIds || []).map(String),
    ...(todo.watcherIds || []).map(String),
  ];
  if (!participants.includes(viewerId) && !(await hasPermission("todos_view"))) {
    return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });
  }

  const att = todo.attachments.find((a) => a.storedName === storedName);
  if (!att) return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });

  try {
    const buffer = await readFile(todoUploadPath(todoId, storedName));
    return new NextResponse(new Uint8Array(buffer), {
      headers: {
        ...headers,
        "Content-Type": att.mimeType,
        "Content-Disposition": `inline; filename="${encodeURIComponent(att.filename)}"`,
        "Cache-Control": "private, max-age=0, no-store",
      },
    });
  } catch {
    return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ todoId: string; storedName: string }> }) {
  const headers = corsHeaders(request);
  const viewerId = await getSessionClientId();
  if (!viewerId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { todoId, storedName } = await params;
  await deleteTodoAttachmentAction(todoId, storedName);
  return NextResponse.json({ ok: true }, { headers });
}
