// app/api/domains/[id]/route.ts
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

interface RouteParams {
  params: { id: string };
}

export async function DELETE(req: NextRequest, { params }: RouteParams) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = params;
    if (!id) {
      return NextResponse.json({ error: "Domain id is required" }, { status: 400 });
    }

    const domain = await prisma.domain.findUnique({ where: { id } });
    if (!domain) {
      return NextResponse.json({ error: "Domain not found" }, { status: 404 });
    }

    // Prisma cascade (onDelete: Cascade on TempEmail.domain, and on
    // InboundMessage.tempEmail) handles the full teardown of every temp
    // email and message under this domain in a single transaction.
    await prisma.domain.delete({ where: { id } });

    return NextResponse.json({ success: true });
  } catch (err) {
    console.error(`DELETE /api/domains/${params.id} failed:`, err);
    return NextResponse.json(
      { error: "Failed to delete domain" },
      { status: 500 }
    );
  }
}
