import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { THREADS_MAX_CHARS } from "@/lib/utils";
import { getActiveAccountId } from "@/lib/account-context";
import { authErrorResponse } from "@/lib/auth/api";
import { isAccountInUserScope, requireUserAccountScope } from "@/lib/auth/user-scope";

async function findOwnedDraft(id: string) {
  const { accountIds } = await requireUserAccountScope(await getActiveAccountId());
  const draft = await prisma.outreachDraft.findUnique({
    where: { id },
    include: {
      outreachTarget: {
        include: { scanItem: { include: { scan: true } }, _count: { select: { drafts: true } } },
      },
    },
  });
  if (!draft || !isAccountInUserScope(accountIds, draft.outreachTarget.scanItem.scan.accountId)) {
    return null;
  }
  return draft;
}

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = (await request.json()) as { text?: string; status?: string };

    if (body.text && body.text.length > THREADS_MAX_CHARS) {
      return NextResponse.json({ error: `超過 ${THREADS_MAX_CHARS} 字上限` }, { status: 400 });
    }
    const existing = await findOwnedDraft(id);
    if (!existing) return NextResponse.json({ error: "找不到留言草稿" }, { status: 404 });

    const draft = await prisma.outreachDraft.update({
      where: { id },
      data: {
        ...(body.text !== undefined && { text: body.text }),
        ...(body.status !== undefined && { status: body.status }),
      },
    });

    return NextResponse.json({ draft });
  } 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,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const draft = await findOwnedDraft(id);
    if (!draft) return NextResponse.json({ error: "找不到留言草稿" }, { status: 404 });
    if (draft.status === "PUBLISHED") {
      return NextResponse.json(
        { error: "這則留言已發布到 Threads，不能只刪除本地紀錄" },
        { status: 409 }
      );
    }

    const removeTarget = draft.outreachTarget._count.drafts <= 1;
    if (removeTarget) {
      await prisma.outreachTarget.delete({ where: { id: draft.outreachTargetId } });
    } else {
      await prisma.outreachDraft.delete({ where: { id } });
    }
    return NextResponse.json({ deleted: true, removedTarget: removeTarget });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    const message = error instanceof Error ? error.message : "刪除留言草稿失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
