/**
 * POST /api/social/auth/[platform]/authorize
 * Start OAuth flow for a social platform
 *
 * Data-source routing: WU-06 — Convex branch added for social domain.
 * Note: OAuth URL generation is purely external (Meta Graph API) with no DB
 * operations. The data-source check is in place so that when DS_SOCIAL=convex,
 * the authorize flow still works identically (no DB routing needed here).
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getAuthorizationUrl } from "@/lib/services/social-auth.service";
import { socialPlatformSchema } from "@/lib/validators/social-media.validator";
import { getDataSource } from "@/lib/data-source";
import { logger } from "@/lib/logger";
import type { SocialPlatform } from "@/lib/types/social-media.types";

function normalizeBaseUrl(value?: string | null): string | null {
  if (!value) return null;
  try {
    return new URL(value).origin;
  } catch {
    return null;
  }
}

function resolveOAuthCallbackBaseUrl(request: NextRequest): string {
  const candidates = [
    process.env.SOCIAL_OAUTH_BASE_URL,
    process.env.NGROK_URL,
    process.env.NEXTAUTH_URL,
    process.env.NEXT_PUBLIC_APP_URL,
    request.nextUrl.origin,
  ];

  for (const candidate of candidates) {
    const normalized = normalizeBaseUrl(candidate);
    if (normalized) return normalized;
  }

  return request.nextUrl.origin;
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ platform: string }> },
) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const { platform } = await params;
    const parsed = socialPlatformSchema.safeParse(platform.toUpperCase());
    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: "Invalid platform" },
        { status: 400 },
      );
    }

    const validPlatform = parsed.data as SocialPlatform;
    const oauthBaseUrl = resolveOAuthCallbackBaseUrl(request);
    const redirectUrl = `${oauthBaseUrl}/api/social/auth/${platform}/callback`;

    // -- Convex data-source branch ------------------------------------------
    // OAuth authorization URL generation has no DB operations.
    // The same service call works regardless of data source.
    // Log data source for observability.
    if (getDataSource("social") === "convex") {
      logger.info("Social OAuth authorize via Convex data-source", {
        platform: validPlatform,
        userId: user.userId,
      });
    }

    const { url, csrfToken } = await getAuthorizationUrl(
      validPlatform,
      user.userId,
      redirectUrl,
    );

    return NextResponse.json({ success: true, data: { url, csrfToken } });
  } catch (error) {
    logger.error("Failed to start OAuth", { error });
    return NextResponse.json(
      { success: false, error: "Failed to start authorization" },
      { status: 500 },
    );
  }
}
