/**
 * DELETE /api/brands/[brandId]/assets/[assetId]
 *
 * Removes the BrandAsset row and (best-effort) the underlying file on
 * disk. Auto-imported logos from BrandProfile are allowed to be deleted
 * — the next list call will re-seed them if the profile still has a
 * logoUrl.
 */

import { NextResponse } from "next/server";
import { promises as fs } from "fs";
import path from "path";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function DELETE(
  _req: Request,
  { params }: { params: { brandId: string; assetId: string } },
) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const brand = await prisma.brand.findUnique({
    where: { id: params.brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const asset = await prisma.brandAsset.findUnique({ where: { id: params.assetId } });
  if (!asset || asset.brandId !== params.brandId) {
    return NextResponse.json({ error: "Asset not found" }, { status: 404 });
  }

  // Best-effort file removal — only touch paths inside our upload tree.
  if (asset.url.startsWith(`/uploads/${params.brandId}/`)) {
    try {
      const filePath = path.join(process.cwd(), "public", asset.url);
      await fs.unlink(filePath);
    } catch {
      /* ignore — the row is authoritative, file cleanup is best effort */
    }
  }

  await prisma.brandAsset.delete({ where: { id: params.assetId } });
  return NextResponse.json({ ok: true });
}
