/**
 * Server Actions for OTP Login
 *
 * Handles OTP verification and session creation on the server
 * This avoids CSRF issues and properly creates NextAuth sessions
 */

"use server";

import { signIn as authSignIn } from "@/lib/auth";
import { redirect } from "next/navigation";

/**
 * Create session after OTP verification
 *
 * This server action is called after OTP is verified on the client
 * It creates a proper NextAuth session for dashboard access
 *
 * @param email - User's email address
 * @param redirectPath - Where to redirect after session creation
 * @returns Never (redirects)
 */
export async function createSessionFromOTP(
  email: string,
  redirectPath: string = "/en/dashboard",
) {
  try {
    console.log("[OTP Session] Creating NextAuth session for:", email);

    // Use NextAuth signIn with special OTP-verified flag
    // Note: redirect is handled separately to avoid confusion with thrown redirects
    const result = await authSignIn("credentials", {
      email,
      password: "__OTP_VERIFIED__",
      redirect: false, // Don't auto-redirect, we'll handle it manually
    });

    console.log("[OTP Session] SignIn result:", result);

    if (result?.error) {
      console.error("[OTP Session] Failed to create session:", result.error);
      throw new Error("Failed to create session: " + result.error);
    }

    if (!result?.ok) {
      console.error("[OTP Session] SignIn not OK:", result);
      throw new Error("Failed to create session - signIn returned not OK");
    }

    console.log(
      "[OTP Session] NextAuth session created successfully, redirecting to:",
      redirectPath,
    );

    // Manually redirect after successful session creation
    redirect(redirectPath);
  } catch (error) {
    console.error("[OTP Session] Error:", error);

    // If error is from redirect (expected), it's actually success
    if (error instanceof Error && error.message.includes("NEXT_REDIRECT")) {
      // This is expected - redirect throws
      console.log(
        "[OTP Session] Redirect thrown (expected), session created successfully",
      );
      throw error;
    }

    // Real error - log and re-throw
    console.error("[OTP Session] Real error during session creation:", error);
    throw new Error("Failed to create session");
  }
}
