import { NextResponse } from "next/server";
import { getActiveAccountConnectionSettings } from "@/lib/account-connection-settings";
import { getActiveAccountProfile } from "@/lib/account-context";
import {
  accountHasThreadsToken,
  isThreadsAppConfigured,
  maskToken,
} from "@/lib/threads-api";
import { apiRouteErrorResponse } from "@/lib/auth/api";

export async function GET() {
  try {
    const [account, connection] = await Promise.all([
      getActiveAccountProfile(),
      getActiveAccountConnectionSettings(),
    ]);
    return NextResponse.json({
      connected: accountHasThreadsToken(account),
      publishViaApi: connection.publishViaApi,
      accountId: account?.id ?? null,
      accountName: account?.displayName ?? account?.username ?? null,
      userId: account?.threadsUserId ?? null,
      tokenExpiresAt: account?.threadsTokenExpiresAt?.toISOString() ?? null,
      tokenMasked: maskToken(account?.threadsAccessToken),
      appIdConfigured: isThreadsAppConfigured(),
    });
  } catch (error) {
    return apiRouteErrorResponse(error, "threads/status");
  }
}
