import { NextResponse } from "next/server";
import { DepartmentKey } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canAccessProjects, mapProjectCaptureEvidence } from "@/lib/projects/persistence";

function parseIsoDate(value: string | null): Date | null {
  if (!value) {
    return null;
  }

  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return null;
  }

  return parsed;
}

export async function GET(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canAccessProjects(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const url = new URL(request.url);
  const initiativeId = url.searchParams.get("initiativeId")?.trim() || undefined;
  const taskId = url.searchParams.get("taskId")?.trim() || undefined;
  const uploadedById = url.searchParams.get("uploadedById")?.trim() || undefined;
  const from = parseIsoDate(url.searchParams.get("from"));
  const to = parseIsoDate(url.searchParams.get("to"));
  const query = url.searchParams.get("q")?.trim() || undefined;

  const records = await prisma.projectCaptureEvidence.findMany({
    where: {
      department: DepartmentKey.proyectos,
      initiativeId,
      taskId,
      uploadedById,
      ...(from || to
        ? {
            createdAt: {
              ...(from ? { gte: from } : {}),
              ...(to ? { lte: to } : {}),
            },
          }
        : {}),
      ...(query
        ? {
            OR: [
              {
                title: {
                  contains: query,
                  mode: "insensitive",
                },
              },
              {
                note: {
                  contains: query,
                  mode: "insensitive",
                },
              },
            ],
          }
        : {}),
    },
    include: {
      uploadedBy: {
        select: {
          name: true,
          email: true,
        },
      },
      initiative: {
        select: {
          id: true,
          name: true,
        },
      },
      task: {
        select: {
          id: true,
          title: true,
        },
      },
    },
    orderBy: [{ createdAt: "desc" }],
    take: 400,
  });

  return NextResponse.json({
    ok: true,
    evidence: records.map((record) => ({
      ...mapProjectCaptureEvidence(record),
      initiativeName: record.initiative?.name ?? null,
      taskTitle: record.task?.title ?? null,
    })),
  });
}
