import { NextResponse } from "next/server"

import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { storageProvider } from "@/shared/lib/storage-provider"
import {
  deleteFileAttachments,
  getFileAttachmentsByIds,
} from "@/modules/files/data-access"

export const dynamic = "force-dynamic"

/**
 * POST /api/files/batch-delete
 * 批量删除文件（需要 FILE_DELETE 权限）
 * Body: { ids: string[] }
 */
export async function POST(req: Request) {
  try {
    await requirePermission(Permissions.FILE_DELETE)

    const body = (await req.json().catch(() => null)) as { ids?: unknown } | null
    const ids = Array.isArray(body?.ids) ? body!.ids.filter((x): x is string => typeof x === "string") : []

    if (ids.length === 0) {
      return NextResponse.json(
        { success: false, message: "No file ids provided" },
        { status: 400 }
      )
    }

    // 先查出文件记录，以便删除磁盘文件
    const files = await getFileAttachmentsByIds(ids)

    // 删除磁盘文件（静默失败）
    await Promise.all(
      files.map((f) => storageProvider.delete(f.storagePath).catch(() => undefined))
    )

    const result = await deleteFileAttachments(ids)

    return NextResponse.json({
      success: result.success,
      message: `Deleted ${result.deletedCount} file(s)`,
      deletedCount: result.deletedCount,
      failedIds: result.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 })
  }
}
