"use server";

import { signIn } from "@/lib/auth";
import { AuthError } from "next-auth";
import { isRedirectError } from "next/dist/client/components/redirect";

/**
 * Login with credentials - Returns structured error data for bilingual display
 *
 * Error codes from lib/auth.ts:
 * - USER_NOT_FOUND: Email doesn't exist in database
 * - INVALID_PASSWORD:N: Wrong password (N = attempts remaining)
 * - ACCOUNT_LOCKED:N: Account locked for N minutes
 * - NO_PASSWORD_SET: Account uses OAuth only (no password)
 * - MISSING_CREDENTIALS: Email or password not provided
 *
 * Returns:
 * - { success: true } on successful login
 * - { errorCode: string, metadata?: object } on error (client will format message)
 */
export async function loginWithCredentials(
  email: string,
  password: string,
  redirectTo: string,
) {
  try {
    await signIn("credentials", {
      email,
      password,
      redirectTo,
    });
    return { success: true };
  } catch (error) {
    // NextAuth throws NEXT_REDIRECT on successful login - this is expected behavior
    if (isRedirectError(error)) {
      throw error; // Re-throw to allow Next.js to handle the redirect
    }

    if (error instanceof AuthError) {
      // Extract the underlying error message from NextAuth
      const cause = error.cause as any;
      const errorMessage = cause?.err?.message || error.message || "";

      // 🎯 USER NOT FOUND - Account doesn't exist
      if (errorMessage.includes("USER_NOT_FOUND")) {
        return { errorCode: "USER_NOT_FOUND" };
      }

      // 🎯 INVALID PASSWORD - Wrong password with remaining attempts
      if (errorMessage.includes("INVALID_PASSWORD")) {
        const match = errorMessage.match(/INVALID_PASSWORD:(\d+)/);
        const remainingAttempts = match ? parseInt(match[1]) : 0;
        return {
          errorCode: "INVALID_PASSWORD",
          metadata: { remainingAttempts },
        };
      }

      // 🎯 ACCOUNT LOCKED - Too many failed attempts
      if (errorMessage.includes("ACCOUNT_LOCKED")) {
        const match = errorMessage.match(/ACCOUNT_LOCKED:(\d+)/);
        const lockMinutes = match ? parseInt(match[1]) : 30;
        return {
          errorCode: "ACCOUNT_LOCKED",
          metadata: { lockMinutes },
        };
      }

      // 🎯 NO PASSWORD SET - OAuth-only account
      if (errorMessage.includes("NO_PASSWORD_SET")) {
        return { errorCode: "NO_PASSWORD_SET" };
      }

      // 🎯 MISSING CREDENTIALS
      if (errorMessage.includes("MISSING_CREDENTIALS")) {
        return { errorCode: "MISSING_CREDENTIALS" };
      }

      // Generic CredentialsSignin error (fallback)
      if (error.type === "CredentialsSignin") {
        return { errorCode: "CREDENTIALS_SIGNIN" };
      }

      // Other auth errors
      return { errorCode: "AUTH_ERROR" };
    }

    // Unexpected errors
    throw error;
  }
}

/**
 * Create NextAuth session after OTP verification
 * Uses the special __OTP_VERIFIED__ password to bypass normal password check
 */
export async function createOTPSession(email: string, redirectTo: string) {
  try {
    await signIn("credentials", {
      email,
      password: "__OTP_VERIFIED__",
      redirectTo,
    });
    return { success: true };
  } catch (error) {
    // NextAuth throws NEXT_REDIRECT on successful login - this is expected behavior
    if (isRedirectError(error)) {
      throw error; // Re-throw to allow Next.js to handle the redirect
    }

    if (error instanceof AuthError) {
      console.error("[OTP Session Error]:", error);
      return { errorCode: "SESSION_ERROR", message: error.message };
    }

    // Unexpected errors
    console.error("[OTP Session Unexpected Error]:", error);
    throw error;
  }
}
