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

import ApiClient from "./ApiClient";

/**
 * MeService - Handles User Profile API requests
 *
 * Backend API: GET /api/v1/me
 * Documentation: cloud/maplepress-backend/docs/API.md (lines 374-413)
 *
 * Purpose: Get the authenticated user's profile information from the JWT token.
 * This endpoint extracts user data directly from the JWT claims (no database query).
 * Useful for displaying user information in the dashboard and verifying the current
 * authenticated user's identity.
 */

/**
 * Get the current authenticated user's profile
 *
 * @returns {Promise<Object>} User profile data
 * @throws {Error} If authentication fails or token is invalid
 *
 * Response format (transformed to camelCase):
 * {
 *   userId: string,    // User's unique identifier (UUID)
 *   email: string,     // User's email address
 *   name: string,      // User's full name
 *   role: string,      // User's role (e.g., "owner", "admin", "user")
 *   tenantId: string   // User's tenant/organization ID (UUID)
 * }
 */
async function getMe() {
  try {
    // Make authenticated GET request
    // No request body needed - all data comes from JWT token
    const response = await ApiClient.get("/api/v1/me");

    // Transform response to camelCase for frontend
    return {
      userId: response.user_id,
      email: response.email,
      name: response.name,
      role: response.role,
      tenantId: response.tenant_id,
    };
  } catch (error) {
    // Map backend errors to user-friendly messages
    const message = error.message?.toLowerCase() || "";

    if (message.includes("unauthorized") || message.includes("401")) {
      throw new Error(
        "Authentication required. Please log in to continue."
      );
    }

    if (message.includes("token")) {
      throw new Error(
        "Invalid or expired authentication token. Please log in again."
      );
    }

    // Generic error
    throw new Error(
      error.message || "Failed to fetch user profile. Please try again."
    );
  }
}

/**
 * Check if the current user has a specific role
 *
 * @param {string} requiredRole - Role to check for (e.g., "owner", "admin", "user")
 * @returns {Promise<boolean>} True if user has the required role
 */
async function hasRole(requiredRole) {
  try {
    const profile = await getMe();
    return profile.role === requiredRole;
  } catch (error) {
    console.error("[MeService] Failed to check role:", error);
    return false;
  }
}

/**
 * Get the current user's tenant ID
 *
 * @returns {Promise<string|null>} Tenant ID or null if not available
 */
async function getTenantId() {
  try {
    const profile = await getMe();
    return profile.tenantId;
  } catch (error) {
    console.error("[MeService] Failed to get tenant ID:", error);
    return null;
  }
}

/**
 * Verify that the current user matches a specific user ID
 *
 * @param {string} userId - User ID to verify against
 * @returns {Promise<boolean>} True if the current user matches the provided ID
 */
async function isCurrentUser(userId) {
  try {
    const profile = await getMe();
    return profile.userId === userId;
  } catch (error) {
    console.error("[MeService] Failed to verify user:", error);
    return false;
  }
}

// Export service
const MeService = {
  getMe,
  hasRole,
  getTenantId,
  isCurrentUser,
};

export default MeService;
