// File: src/services/API/LoginService.js

/**
 * LoginService
 *
 * Handles user login API calls to the MaplePress backend.
 * Based on backend API: POST /api/v1/login
 */

import ApiClient from "./ApiClient.js";

/**
 * Login with email and password
 *
 * @param {Object} credentials - Login credentials
 * @param {string} credentials.email - User's email address
 * @param {string} credentials.password - User's password
 *
 * @returns {Promise<Object>} Login response with tokens
 * @throws {Error} Login error with message
 */
async function login(credentials) {
  try {
    console.log("[LoginService] Login attempt for:", credentials.email);

    // Validate required fields
    if (!credentials.email) {
      throw new Error("Email is required");
    }
    if (!credentials.password) {
      throw new Error("Password is required");
    }

    // Prepare request body matching backend LoginRequestDTO structure
    const requestBody = {
      email: credentials.email,
      password: credentials.password,
    };

    // Call backend API
    const response = await ApiClient.post("/api/v1/login", requestBody);

    console.log("[LoginService] Login successful:", response.user_id);

    // Return response matching backend structure
    return {
      // User details
      userId: response.user_id,
      userEmail: response.user_email,
      userName: response.user_name,
      userRole: response.user_role,

      // Tenant details
      tenantId: response.tenant_id,

      // Authentication tokens
      sessionId: response.session_id,
      accessToken: response.access_token,
      accessExpiry: new Date(response.access_expiry),
      refreshToken: response.refresh_token,
      refreshExpiry: new Date(response.refresh_expiry),

      loginAt: new Date(response.login_at),
    };
  } catch (error) {
    console.error("[LoginService] Login failed:", error);

    // Parse and re-throw with user-friendly message
    let errorMessage = "Login failed. Please try again.";

    if (error.message) {
      // Map backend error messages to user-friendly messages
      if (
        error.message.includes("Invalid email or password") ||
        error.message.includes("Unauthorized") ||
        error.message.includes("invalid credentials")
      ) {
        // Check if there's information about remaining attempts
        if (error.message.includes("attempts remaining")) {
          errorMessage = error.message; // Use the detailed message from backend
        } else {
          errorMessage = "Invalid email or password. Please try again.";
        }
      } else if (
        error.message.includes("locked") ||
        error.message.includes("Too many")
      ) {
        errorMessage =
          "Account temporarily locked due to too many failed attempts. Please try again later.";
      } else if (error.message.includes("email")) {
        errorMessage = "Invalid email address.";
      } else if (error.message.includes("required")) {
        errorMessage = error.message;
      } else {
        errorMessage = error.message;
      }
    }

    throw new Error(errorMessage);
  }
}

const LoginService = {
  login,
};

export default LoginService;
