/**
 * GET /api/social/auth/[platform]/callback
 * Handle OAuth callback from social platform
 *
 * Data-source routing: WU-06 — Convex branch added for social domain.
 * The OAuth callback involves external token exchange (Meta Graph API) tightly
 * coupled with account creation in the service layer. When DS_SOCIAL=convex,
 * we call the existing service (which writes to Prisma) and then replicate the
 * created accounts to Convex via upsertAccount mutation for dual-write. Once
 * the service layer is fully migrated, the Prisma writes inside handleCallback
 * will be removed.
 */

import { NextRequest, NextResponse } from "next/server";
import { handleCallback } 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 resolveAppBaseUrl(request: NextRequest): string {
  const candidates = [
    process.env.NEXT_PUBLIC_APP_URL,
    process.env.NEXTAUTH_URL,
    request.nextUrl.origin,
  ];

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

  return request.nextUrl.origin;
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ platform: string }> },
) {
  try {
    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 { searchParams } = request.nextUrl;
    const code = searchParams.get("code");
    const state = searchParams.get("state");

    if (!code || !state) {
      return NextResponse.json(
        { success: false, error: "Missing code or state" },
        { status: 400 },
      );
    }

    // handleCallback performs external token exchange + Prisma account creation
    const accounts = await handleCallback(validPlatform, code, state);

    // -- Convex data-source branch (dual-write) --------------------------------
    // Replicate created accounts to Convex. The handleCallback service already
    // wrote to Prisma; this ensures Convex is in sync when DS_SOCIAL=convex.
    if (getDataSource("social") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");

        for (const account of accounts) {
          await convexMutation("social/mutations:upsertAccount", {
            userId: account.userId,
            platform: account.platform,
            platformAccountId: account.platformAccountId,
            accountName: account.accountName,
            accessToken: "", // Tokens are encrypted in Prisma; Convex stores separately
            tokenExpiry: account.tokenExpiry
              ? account.tokenExpiry.getTime()
              : undefined,
            metadata: account.metadata ?? undefined,
          });
        }

        logger.info("Social accounts replicated to Convex", {
          platform: validPlatform,
          count: accounts.length,
        });
      } catch (convexError) {
        // Non-blocking: Prisma is still the primary source of truth
        logger.warn("[Convex fallback] social callback dual-write:", {
          error:
            convexError instanceof Error
              ? convexError.message
              : String(convexError),
        });
      }
    }

    // Redirect to dashboard with success
    const dashboardUrl = new URL("/en/dashboard", resolveAppBaseUrl(request));
    dashboardUrl.searchParams.set("tab", "social-media");
    dashboardUrl.searchParams.set("connected", String(accounts.length));
    return NextResponse.redirect(dashboardUrl);
  } catch (error) {
    logger.error("OAuth callback failed", { error });
    const dashboardUrl = new URL("/en/dashboard", resolveAppBaseUrl(request));
    dashboardUrl.searchParams.set("tab", "social-media");
    dashboardUrl.searchParams.set("error", "connection_failed");
    return NextResponse.redirect(dashboardUrl);
  }
}
