import { NextResponse } from "next/server"

import { rateLimit, rateLimitKey, rateLimitHeaders, RATE_LIMIT_RULES } from "@/shared/lib/rate-limit"
import { PermissionDeniedError } from "@/shared/lib/errors"
import { uploadFileAction } from "@/modules/files/actions"

export const dynamic = "force-dynamic"

/**
 * POST /api/upload
 *
 * 文件上传入口：解析 multipart/form-data，应用速率限制，
 * 然后委托给 `uploadFileAction` Server Action 执行权限校验、
 * Zod 校验、磁盘写入与 DB 落库。
 */
export async function POST(req: Request) {
  try {
    const formData = await req.formData()
    const file = formData.get("file")
    const targetType = formData.get("targetType")
    const targetId = formData.get("targetId")

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

    // Rate limit per uploader identity (resolved inside action via session).
    // Use a coarse IP-based key as fallback for pre-auth rejection.
    const limitKey = rateLimitKey("upload", req.headers.get("x-forwarded-for") ?? "anon")
    const limit = await rateLimit({ key: limitKey, ...RATE_LIMIT_RULES.UPLOAD })
    if (!limit.success) {
      return NextResponse.json(
        { success: false, message: "Upload rate limit exceeded. Please try again later." },
        { status: 429, headers: rateLimitHeaders(limit) }
      )
    }

    const result = await uploadFileAction(file, {
      targetType: typeof targetType === "string" ? targetType : null,
      targetId: typeof targetId === "string" ? targetId : null,
    })

    if (!result.success || !result.data) {
      const status =
        result.message?.includes("auth_required") ? 401
        : result.message?.includes("Permission denied") || result.message?.includes("not allowed") ? 403
        : result.message?.includes("exceeds") ? 413
        : result.message?.includes("empty") || result.message?.includes("No file") ? 400
        : 500
      return NextResponse.json(
        { success: false, message: result.message ?? "Upload failed" },
        { status }
      )
    }

    return NextResponse.json({
      success: true,
      ...result.data,
    })
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      return NextResponse.json(
        { success: false, message: e.message },
        { status: 403 }
      )
    }
    const message = e instanceof Error ? e.message : "Upload failed"
    return NextResponse.json({ success: false, message }, { status: 500 })
  }
}
