import { auth } from "@/auth";
import { NextRequest, NextResponse } from "next/server";
import * as XLSX from "xlsx";
import { parseSheet } from "@/lib/po-import-parser";

export type { ParsedImportLine, ParsedImport } from "@/lib/po-import-parser";

export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { role } = session.user;
  if (!["MANAGER", "SUPERUSER", "ADMIN"].includes(role)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  let formData: FormData;
  try {
    formData = await req.formData();
  } catch {
    return NextResponse.json({ error: "Invalid form data" }, { status: 400 });
  }

  const file = formData.get("file") as File | null;
  if (!file) return NextResponse.json({ error: "No file provided" }, { status: 400 });

  const buffer = Buffer.from(await file.arrayBuffer());
  let workbook: XLSX.WorkBook;
  try {
    workbook = XLSX.read(buffer, { type: "buffer" });
  } catch {
    return NextResponse.json(
      { error: "Could not parse Excel file. Ensure it is a valid .xlsx file." },
      { status: 400 }
    );
  }

  const results = [];
  for (const sheetName of workbook.SheetNames) {
    const sheet = workbook.Sheets[sheetName];
    try {
      const parsed = parseSheet(sheet);
      if (parsed.lineItems.length > 0) results.push(parsed);
    } catch {
      // skip unparseable sheets
    }
  }

  if (results.length === 0) {
    return NextResponse.json(
      { error: "No valid purchase order data found in the file." },
      { status: 400 }
    );
  }

  return NextResponse.json({ results });
}
