import { NextRequest, NextResponse } from "next/server";
import { headers } from "next/headers";
import { eq } from "drizzle-orm";

import { auth } from "@/lib/auth";
import { db } from "@/db";
import { upload } from "@/db/schema";
import { getOssClient } from "@/lib/oss";

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  // 鉴权：必须登录且是 admin
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session || session.user.role !== "admin") {
    return NextResponse.json({ error: "未授权" }, { status: 401 });
  }

  const { id } = await params;

  // 查询上传记录
  const [record] = await db
    .select()
    .from(upload)
    .where(eq(upload.id, id))
    .limit(1);

  if (!record) {
    return NextResponse.json({ error: "记录不存在" }, { status: 404 });
  }

  try {
    const ossClient = getOssClient();

    // 先从 OSS 删除文件
    await ossClient.delete(record.ossKey);

    // 再从数据库删除记录
    await db.delete(upload).where(eq(upload.id, id));

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("[删除文件失败]", error);
    return NextResponse.json(
      { error: "删除失败，请稍后重试" },
      { status: 500 }
    );
  }
}
