import { NextResponse } from "next/server"

import { PermissionDeniedError } from "@/shared/lib/errors"
import { getFileAction, deleteFileAction } from "@/modules/files/actions"

export const dynamic = "force-dynamic"

interface RouteContext {
  params: Promise<{ id: string }>
}

/**
 * GET /api/files/[id]
 *
 * 获取文件元数据。委托给 `getFileAction` 执行权限校验与
 * ownership 检查，防止横向越权。
 */
export async function GET(_req: Request, ctx: RouteContext) {
  try {
    const { id } = await ctx.params
    const result = await getFileAction(id)

    if (!result.success || !result.data) {
      const status =
        result.message?.includes("auth_required") ? 401
        : result.message?.includes("Permission denied") ? 403
        : result.message?.includes("not found") ? 404
        : 500
      return NextResponse.json(
        { success: false, message: result.message ?? "Failed to fetch file" },
        { status }
      )
    }

    return NextResponse.json({ success: true, file: 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 : "Failed to fetch file"
    return NextResponse.json({ success: false, message }, { status: 500 })
  }
}

/**
 * DELETE /api/files/[id]
 *
 * 删除文件。委托给 `deleteFileAction` 执行权限校验、
 * storageProvider 删除与 DB 落库。
 */
export async function DELETE(_req: Request, ctx: RouteContext) {
  try {
    const { id } = await ctx.params
    const result = await deleteFileAction(id)

    if (!result.success) {
      const status =
        result.message?.includes("auth_required") ? 401
        : result.message?.includes("Permission denied") ? 403
        : result.message?.includes("not found") ? 404
        : 500
      return NextResponse.json(
        { success: false, message: result.message ?? "Failed to delete file" },
        { status }
      )
    }

    return NextResponse.json({ success: true, message: "File deleted" })
  } 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 delete file"
    return NextResponse.json({ success: false, message }, { status: 500 })
  }
}
