/**
 * GET /api/social/accounts
 * List connected social media accounts for the current user
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getConnectedAccounts } from "@/lib/services/social-auth.service";
import { logger } from "@/lib/logger";
import { convexQuery } from "@/lib/convex-client";
export async function GET(request: NextRequest) {
  // Convex branch — additive, falls through to Prisma on error or null result
  try {
    const { convexQuery } = await import("@/lib/convex-client");
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }
    const result = await convexQuery("social/queries:getAccounts", {
      userId: user.userId,
    });
    if (result !== null) {
      return NextResponse.json({ accounts: result, success: true });
    }
  } catch (err) {
    logger.error("Convex getAccounts failed, falling through to Prisma", {
      err,
    });
  }

  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const accounts = await getConnectedAccounts(user.userId);
    return NextResponse.json({ success: true, data: accounts });
  } catch (error) {
    logger.error("Failed to list social accounts", { error });
    return NextResponse.json(
      { success: false, error: "Failed to list accounts" },
      { status: 500 },
    );
  }
}
