import { NextResponse } from "next/server";
import { getActiveAccountProfile } from "@/lib/account-context";
import {
  fromAccountPublic,
  getActiveAccountConnectionSettings,
  migrateUserConnectionSettingsIfNeeded,
  updateActiveAccountConnectionSettings,
} from "@/lib/account-connection-settings";
import { parseSearchSourceMode } from "@/lib/search/source-mode";
import type { AccountConnectionSettings } from "@/lib/account-connection-settings";
import { authErrorResponse } from "@/lib/auth/api";
import { requireSessionUser } from "@/lib/auth/session";
export async function GET() {
  try {
    const user = await requireSessionUser();
    await migrateUserConnectionSettingsIfNeeded(user.id);

    const account = await getActiveAccountProfile();
    if (!account) {
      return NextResponse.json({
        accountId: null,
        accountName: null,
        connection: null,
      });
    }

    const connection = await getActiveAccountConnectionSettings();

    return NextResponse.json({
      accountId: account.id,
      accountName: account.displayName ?? account.username ?? "未命名帳號",
      username: account.username,
      connection: fromAccountPublic(connection),
    });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    console.error("[accounts/connection GET]", error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "載入連線設定失敗" },
      { status: 500 }
    );
  }
}

export async function PATCH(request: Request) {
  try {
    const user = await requireSessionUser();
    const body = (await request.json()) as Partial<{
      searchViaApi: boolean;
      searchSourceMode: string;
      publishViaApi: boolean;
      devMode: boolean;
      scrapeReplies: boolean;
      repliesPerPost: number;
      publishHeaded: boolean;
      playwrightDebug: boolean;
    }>;

    const { searchSourceMode: rawSourceMode, ...rest } = body;
    const patch: Partial<AccountConnectionSettings> = {
      ...rest,
      ...(rawSourceMode !== undefined && {
        searchSourceMode: parseSearchSourceMode(rawSourceMode),
      }),
    };

    const { account } = await updateActiveAccountConnectionSettings(user.id, patch);

    return NextResponse.json({
      accountId: account.id,
      accountName: account.displayName ?? account.username ?? "未命名帳號",
      connection: fromAccountPublic({
        searchViaApi: account.searchViaApi,
        searchSourceMode: parseSearchSourceMode(account.searchSourceMode),
        publishViaApi: account.publishViaApi,
        devMode: account.devMode,
        scrapeReplies: account.scrapeReplies,
        repliesPerPost: account.repliesPerPost,
        publishHeaded: account.publishHeaded,
        playwrightDebug: account.playwrightDebug,
      }),
    });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    if (error instanceof Error && error.message.includes("經營帳號")) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }
    console.error("[accounts/connection PATCH]", error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "儲存連線設定失敗" },
      { status: 500 }
    );
  }
}
