import { NextRequest, NextResponse } from "next/server";
import { readFile } from "fs/promises";
import { connectDB } from "@/lib/db";
import { Todo } from "@/models/Todo";
import { getSessionClientId } from "@/lib/auth";
import { hasPermission } from "@/lib/adminAuth";
import { todoUploadPath } from "@/lib/uploads";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ todoId: string; filename: string }> }
) {
  const { todoId, filename } = await params;
  const viewerId = await getSessionClientId();
  if (!viewerId) return new NextResponse("Unauthorized", { status: 401 });

  await connectDB();
  const todo = await Todo.findById(todoId)
    .select("attachments assignedToId additionalAssigneeIds watcherIds createdById")
    .lean();
  if (!todo) return new NextResponse("Not found", { status: 404 });

  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 new NextResponse("Not found", { status: 404 });
  }

  const att = todo.attachments.find((a) => a.storedName === filename);
  if (!att) return new NextResponse("Not found", { status: 404 });

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