import { NextResponse } from "next/server"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { parseExcel } from "@/shared/lib/excel"

export const dynamic = "force-dynamic"

const MAX_FILE_SIZE = 10 * 1024 * 1024

export async function POST(req: Request) {
  try {
    await requirePermission(Permissions.USER_MANAGE)

    const formData = await req.formData()
    const file = formData.get("file")

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

    if (file.size === 0) {
      return NextResponse.json(
        { success: false, message: "File is empty" },
        { status: 400 }
      )
    }

    if (file.size > MAX_FILE_SIZE) {
      return NextResponse.json(
        { success: false, message: "File size exceeds 10MB limit" },
        { status: 413 }
      )
    }

    const lowerName = file.name.toLowerCase()
    if (!lowerName.endsWith(".xlsx") && !lowerName.endsWith(".xls")) {
      return NextResponse.json(
        { success: false, message: "Only .xlsx and .xls files are supported" },
        { status: 415 }
      )
    }

    const bytes = Buffer.from(await file.arrayBuffer())
    const sheets = await parseExcel(bytes)

    return NextResponse.json({
      success: true,
      sheets,
      fileName: file.name,
    })
  } catch (e) {
    const message = e instanceof Error ? e.message : "Import failed"
    const status = message.includes("Permission denied") || message.includes("auth_required")
      ? 401
      : 500
    return NextResponse.json({ success: false, message }, { status })
  }
}
