import { NextResponse } from "next/server";
import { ensureCountryAccess, getViewerContextOrNull } from "@/lib/auth";
import { parseExcelImport } from "@/lib/import/parse";
import { ensureUploadScopeCountries, parseUploadScope } from "@/lib/import/scope";

const MAX_IMPORT_FILE_BYTES = 25 * 1024 * 1024;
const ALLOWED_IMPORT_EXTENSIONS = new Set(["xlsx", "xls", "csv"]);

function extensionOf(fileName: string) {
  const ext = fileName.split(".").pop()?.toLowerCase() ?? "";
  return ext;
}

function isSupportedImportFile(file: File) {
  return ALLOWED_IMPORT_EXTENSIONS.has(extensionOf(file.name));
}

export async function POST(request: Request) {
  const viewer = await getViewerContextOrNull();
  if (!viewer) {
    return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
  }
  if (viewer.role !== "admin") {
    return NextResponse.json({ message: "Only admins can import data." }, { status: 403 });
  }

  const formData = await request.formData();
  const file = formData.get("file");
  let uploadScope = null;

  try {
    uploadScope = parseUploadScope(formData.get("scope"));
  } catch (error) {
    return NextResponse.json(
      { message: error instanceof Error ? error.message : "Invalid upload scope." },
      { status: 400 },
    );
  }

  if (!(file instanceof File)) {
    return NextResponse.json({ message: "No file provided." }, { status: 400 });
  }

  if (!isSupportedImportFile(file)) {
    return NextResponse.json(
      { message: "Unsupported file type. Upload .xlsx, .xls, or .csv." },
      { status: 400 },
    );
  }

  if (file.size > MAX_IMPORT_FILE_BYTES) {
    return NextResponse.json(
      { message: "File too large. Max size is 25MB." },
      { status: 400 },
    );
  }

  const buffer = await file.arrayBuffer();
  const parsed = parseExcelImport(buffer);

  try {
    if (parsed.detectedCountries.length > 0) {
      await ensureCountryAccess(parsed.detectedCountries, viewer);
      if (viewer.role === "admin") {
        ensureUploadScopeCountries(parsed.detectedCountries, uploadScope);
      }
    }
  } catch (error) {
    return NextResponse.json(
      {
        message: error instanceof Error ? error.message : "Country access denied.",
        ...parsed,
        parsedRows: parsed.rows.length,
      },
      { status: 403 },
    );
  }

  return NextResponse.json({
    previewRows: parsed.previewRows,
    parsedRows: parsed.rows.length,
    documentBrandCount: Object.keys(parsed.documentBrands).length,
    sentimentRows: parsed.sentimentRows,
    sentimentEmailCount: Object.keys(parsed.sentimentByEmail).length,
    detectedCountries: parsed.detectedCountries,
    warnings: parsed.warnings,
    errors: parsed.errors,
  });
}
