import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getActiveAccountId } from "@/lib/account-context";
import { authErrorResponse } from "@/lib/auth/api";
import { isAccountInUserScope, requireUserAccountScope } from "@/lib/auth/user-scope";
import { syncTopicProductSnapshot } from "@/lib/services/product-catalog";
import { parseMatchTags, serializeMatchTags } from "@/lib/types/product-match";
import { hasProductContext } from "@/lib/types/product-context";

export async function POST(request: Request) {
  try {
    const { brandId, label, context, matchTags } = (await request.json()) as {
      brandId?: string;
      label?: string;
      context?: string;
      matchTags?: string[];
    };

    if (!brandId || !label?.trim()) {
      return NextResponse.json({ error: "請填寫品牌與產品名稱" }, { status: 400 });
    }
    if (!context?.trim() || !hasProductContext(context)) {
      return NextResponse.json({ error: "請填寫產品特色" }, { status: 400 });
    }

    const accountId = await getActiveAccountId();
    const { accountIds } = await requireUserAccountScope(accountId);
    const brand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
    if (!brand || !isAccountInUserScope(accountIds, brand.accountId)) {
      return NextResponse.json({ error: "找不到品牌" }, { status: 404 });
    }

    const product = await prisma.productProfile.create({
      data: {
        accountId: brand.accountId ?? accountId ?? undefined,
        brandId,
        label: label.trim(),
        context: context.trim(),
        matchTags: serializeMatchTags(matchTags ?? []),
      },
    });

    return NextResponse.json({
      product: {
        ...product,
        matchTags: parseMatchTags(product.matchTags),
      },
    });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    const message = error instanceof Error ? error.message : "建立產品失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

export async function PATCH(request: Request) {
  try {
    const { id, label, context, matchTags } = (await request.json()) as {
      id?: string;
      label?: string;
      context?: string;
      matchTags?: string[];
    };

    if (!id) return NextResponse.json({ error: "缺少 id" }, { status: 400 });

    const { accountIds } = await requireUserAccountScope(await getActiveAccountId());
    const existing = await prisma.productProfile.findUnique({ where: { id } });
    if (!existing || !isAccountInUserScope(accountIds, existing.accountId)) {
      return NextResponse.json({ error: "找不到產品" }, { status: 404 });
    }

    if (context !== undefined && !hasProductContext(context)) {
      return NextResponse.json({ error: "請填寫產品特色" }, { status: 400 });
    }

    const product = await prisma.productProfile.update({
      where: { id },
      data: {
        ...(label !== undefined && { label: label.trim() }),
        ...(context !== undefined && { context: context.trim() }),
        ...(matchTags !== undefined && { matchTags: serializeMatchTags(matchTags) }),
      },
    });

    const linkedTopics = await prisma.topic.findMany({
      where: {
        OR: [{ productProfileId: id }, { brandProfileId: existing.brandId }],
      },
      select: { id: true },
    });
    for (const topic of linkedTopics) {
      await syncTopicProductSnapshot(topic.id);
    }

    return NextResponse.json({
      product: {
        ...product,
        matchTags: parseMatchTags(product.matchTags),
      },
    });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    const message = error instanceof Error ? error.message : "更新產品失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  try {
    const id = new URL(request.url).searchParams.get("id");
    if (!id) return NextResponse.json({ error: "缺少 id" }, { status: 400 });

    const { accountIds } = await requireUserAccountScope(await getActiveAccountId());
    const existing = await prisma.productProfile.findUnique({ where: { id } });
    if (!existing || !isAccountInUserScope(accountIds, existing.accountId)) {
      return NextResponse.json({ error: "找不到產品" }, { status: 404 });
    }

    const linked = await prisma.topic.count({ where: { productProfileId: id } });
    if (linked > 0) {
      return NextResponse.json(
        { error: `仍有 ${linked} 個主題指定此產品，請先更換` },
        { status: 400 }
      );
    }

    await prisma.productProfile.delete({ where: { id } });
    return NextResponse.json({ success: true });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    const message = error instanceof Error ? error.message : "刪除產品失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}