import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";

export const dynamic = "force-dynamic";

interface ExternalConverter {
  domain: string;
  nickname: string;
  isActive: boolean;
  registeredAt: string;
}

async function checkBrandAccess(brandId: string, userId: string) {
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return null;
  if (!brand.organization.memberships.some((m) => m.userId === userId)) return null;
  return brand;
}

function getConverters(brand: Awaited<ReturnType<typeof checkBrandAccess>>): ExternalConverter[] {
  if (!brand) return [];
  const raw = (brand as unknown as { externalConverters: unknown }).externalConverters;
  return Array.isArray(raw) ? (raw as ExternalConverter[]) : [];
}

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

  const { brandId } = params;
  const brand = await checkBrandAccess(brandId, user.id);
  if (!brand) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  return NextResponse.json({ converters: getConverters(brand) });
}

export async function POST(
  req: NextRequest,
  { params }: { params: { brandId: string } }
) {
  const user = await getCurrentUser();
  if (!user?.id) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { brandId } = params;
  const brand = await checkBrandAccess(brandId, user.id);
  if (!brand) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const body = await req.json() as { domain?: string; nickname?: string };
  const { domain, nickname } = body;
  if (!domain || typeof domain !== "string") {
    return NextResponse.json({ error: "domain required" }, { status: 400 });
  }

  const normalizedDomain = domain
    .replace(/^https?:\/\//, "")
    .replace(/^www\./, "")
    .split("/")[0]
    .toLowerCase();

  const existing = getConverters(brand);
  const idx = existing.findIndex((c) => c.domain === normalizedDomain);
  const entry: ExternalConverter = {
    domain: normalizedDomain,
    nickname: nickname || normalizedDomain,
    isActive: true,
    registeredAt: idx >= 0 ? existing[idx].registeredAt : new Date().toISOString(),
  };

  const updated = idx >= 0
    ? existing.map((c, i) => (i === idx ? entry : c))
    : [...existing, entry];

  await prisma.brand.update({
    where: { id: brandId },
    data: { externalConverters: updated as unknown as Parameters<typeof prisma.brand.update>[0]["data"]["externalConverters"] },
  });

  return NextResponse.json({ ok: true, converter: entry });
}

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

  const { brandId } = params;
  const brand = await checkBrandAccess(brandId, user.id);
  if (!brand) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const { searchParams } = new URL(req.url);
  const domain = searchParams.get("domain");
  if (!domain) return NextResponse.json({ error: "domain required" }, { status: 400 });

  const existing = getConverters(brand);
  const updated = existing.filter((c) => c.domain !== domain);

  await prisma.brand.update({
    where: { id: brandId },
    data: { externalConverters: updated as unknown as Parameters<typeof prisma.brand.update>[0]["data"]["externalConverters"] },
  });

  return NextResponse.json({ ok: true });
}
