import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canManageHumanCapital, ensureEmployeeProfiles } from "@/lib/human-capital";
import { ensureHumanCapitalWorkspaceBootstrap } from "@/lib/human-capital/workspace";

function matchesQuery(value: string, query: string) {
  return value.toLowerCase().includes(query);
}

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

    if (!canManageHumanCapital(session.user.role, session.user.department)) {
      return NextResponse.json({ error: "Only owner/HC leaders can view files." }, { status: 403 });
    }

    await ensureEmployeeProfiles();
    try {
      await ensureHumanCapitalWorkspaceBootstrap();
    } catch (bootstrapError) {
      console.error("[human-capital/files] workspace bootstrap failed; continuing with existing data.", bootstrapError);
    }

    const { searchParams } = new URL(request.url);
    const query = searchParams.get("search")?.trim().toLowerCase() ?? "";
    const statusFilter = searchParams.get("status")?.trim().toLowerCase() ?? "";
    const locationFilter = searchParams.get("location")?.trim().toLowerCase() ?? "";

    const requirements = await prisma.hrFileRequirement.findMany({
      where: {
        department: "capital_humano",
        isActive: true,
      },
      orderBy: [{ sortOrder: "asc" }, { label: "asc" }],
    });

    const profiles = await prisma.employeeProfile.findMany({
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            department: true,
            departmentRole: true,
          },
        },
      },
      orderBy: [{ updatedAt: "desc" }],
    });

    const userIds = profiles.map((profile) => profile.userId);
    const records = await prisma.hrEmployeeFileRecord.findMany({
      where: {
        userId: { in: userIds },
        requirementId: { in: requirements.map((req) => req.id) },
      },
    });

    const recordsByUser = new Map<string, typeof records>();
    for (const record of records) {
      const list = recordsByUser.get(record.userId) ?? [];
      list.push(record);
      recordsByUser.set(record.userId, list);
    }

    const rows = profiles
      .map((profile) => {
        const list = recordsByUser.get(profile.userId) ?? [];
        const statusByRequirement = new Map(list.map((record) => [record.requirementId, record.status]));

        let requiredMissing = 0;
        let requiredComplete = 0;
        for (const requirement of requirements) {
          if (!requirement.isRequired) {
            continue;
          }
          const status = statusByRequirement.get(requirement.id) ?? "missing";
          if (status === "submitted" || status === "verified") {
            requiredComplete += 1;
          } else {
            requiredMissing += 1;
          }
        }

        const requiredTotal = Math.max(1, requiredComplete + requiredMissing);
        const completionPct = Math.round((requiredComplete / requiredTotal) * 100);

        return {
          userId: profile.userId,
          name: profile.user.name?.trim() || profile.user.email,
          email: profile.user.email,
          department: profile.user.department ?? null,
          departmentRole: profile.user.departmentRole ?? null,
          locationId: profile.locationId ?? null,
          completionPct,
          complete: requiredMissing === 0,
          requiredMissing,
        };
      })
      .filter((row) => {
        if (query) {
          const haystack = `${row.name} ${row.email} ${row.department ?? ""} ${row.departmentRole ?? ""}`;
          if (!matchesQuery(haystack, query)) {
            return false;
          }
        }

        if (locationFilter && (row.locationId ?? "").toLowerCase() !== locationFilter) {
          return false;
        }

        if (statusFilter) {
          if (statusFilter === "complete" && !row.complete) {
            return false;
          }
          if (statusFilter === "incomplete" && row.complete) {
            return false;
          }
        }

        return true;
      });

    return NextResponse.json({ ok: true, files: rows });
  } catch (error) {
    if (
      typeof error === "object" &&
      error !== null &&
      "digest" in error &&
      (error as { digest?: string }).digest === "DYNAMIC_SERVER_USAGE"
    ) {
      throw error;
    }

    console.error("[human-capital/files] GET failed.", error);
    const message = error instanceof Error ? error.message : "Failed to load files.";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
