import { NextResponse } from "next/server"

import { PermissionDeniedError } from "@/shared/lib/errors"
import { batchDeleteFilesAction } from "@/modules/files/actions"

export const dynamic = "force-dynamic"

/**
 * POST /api/files/batch-delete
 *
 * 批量删除文件。委托给 `batchDeleteFilesAction` 执行权限校验、
 * Zod 校验、storageProvider 删除与 DB 落库。
 *
 * Body: { ids: string[] }
 */
export async function POST(req: Request) {
  try {
    const body = await req.json().catch(() => null)
    const ids = body && Array.isArray(body.ids) ? body.ids : null

    const result = await batchDeleteFilesAction(ids)

    if (!result.success || !result.data) {
      const status =
        result.message?.includes("auth_required") ? 401
        : result.message?.includes("Permission denied") ? 403
        : result.message?.includes("No file ids") || result.message?.includes("Cannot delete") ? 400
        : 500
      return NextResponse.json(
        { success: false, message: result.message ?? "Failed to batch delete files" },
        { status }
      )
    }

    return NextResponse.json({
      success: result.data.success,
      message: `Deleted ${result.data.deletedCount} file(s)`,
      deletedCount: result.data.deletedCount,
      failedIds: result.data.failedIds,
    })
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      return NextResponse.json(
        { success: false, message: e.message },
        { status: 403 }
      )
    }
    const message = e instanceof Error ? e.message : "Failed to batch delete files"
    return NextResponse.json({ success: false, message }, { status: 500 })
  }
}
