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";

function monthsBetween(start: Date, end: Date): number {
  const years = end.getUTCFullYear() - start.getUTCFullYear();
  const months = end.getUTCMonth() - start.getUTCMonth();
  const days = end.getUTCDate() - start.getUTCDate();
  return years * 12 + months + (days >= 0 ? 0 : -1);
}

function tenureBand(months: number): string {
  if (months < 12) {
    return "<1y";
  }
  if (months < 36) {
    return "1-3y";
  }
  if (months < 60) {
    return "3-5y";
  }
  return "5y+";
}

function csvEscape(value: string | number | null | undefined) {
  const content = String(value ?? "");
  if (/[\",\\n]/.test(content)) {
    return `\"${content.replace(/\"/g, '\"\"')}\"`;
  }
  return content;
}

export async function GET(request: Request) {
  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 people profiles." }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const query = searchParams.get("search")?.trim().toLowerCase() ?? "";
  const department = searchParams.get("department")?.trim().toLowerCase() ?? "";
  const status = searchParams.get("status")?.trim().toLowerCase() ?? "";
  const requestedTenureBand = searchParams.get("tenureBand")?.trim() ?? "";
  const format = searchParams.get("format")?.trim().toLowerCase();
  const now = new Date();
  await ensureEmployeeProfiles();

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

  const rows = profiles
    .map((profile) => {
      const hireDate = profile.hireDate ?? now;
      const tenureMonths = Math.max(0, monthsBetween(hireDate, now));
      const band = tenureBand(tenureMonths);
      return {
        userId: profile.userId,
        name: profile.user.name?.trim() || profile.user.email,
        email: profile.user.email,
        department: profile.user.department ?? "sin_departamento",
        departmentRole: profile.user.departmentRole ?? "",
        employmentStatus: profile.employmentStatus,
        tenureMonths,
        tenureBand: band,
        hireDate: profile.hireDate ? profile.hireDate.toISOString().slice(0, 10) : null,
      };
    })
    .filter((row) => {
      if (query) {
        const haystack = `${row.name} ${row.email} ${row.department} ${row.departmentRole}`.toLowerCase();
        if (!haystack.includes(query)) {
          return false;
        }
      }

      if (department && row.department.toLowerCase() !== department) {
        return false;
      }

      if (status && row.employmentStatus.toLowerCase() !== status) {
        return false;
      }

      if (requestedTenureBand && row.tenureBand !== requestedTenureBand) {
        return false;
      }

      return true;
    });

  if (format === "csv") {
    const header = ["name", "email", "department", "departmentRole", "employmentStatus", "tenureMonths", "tenureBand", "hireDate"];
    const lines = [
      header.join(","),
      ...rows.map((row) =>
        [
          csvEscape(row.name),
          csvEscape(row.email),
          csvEscape(row.department),
          csvEscape(row.departmentRole),
          csvEscape(row.employmentStatus),
          csvEscape(row.tenureMonths),
          csvEscape(row.tenureBand),
          csvEscape(row.hireDate),
        ].join(",")
      ),
    ].join("\n");

    return new NextResponse(lines, {
      headers: {
        "Content-Type": "text/csv; charset=utf-8",
        "Content-Disposition": "attachment; filename=human-capital-people.csv",
      },
    });
  }

  return NextResponse.json({
    ok: true,
    people: rows,
  });
}
