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

import ApiClient from "./ApiClient";

/**
 * HelloService - Handles Hello API requests
 *
 * Backend API: POST /api/v1/hello
 * Documentation: cloud/maplepress-backend/docs/API.md (lines 326-372)
 *
 * Purpose: A simple authenticated endpoint that returns a personalized greeting message.
 * This endpoint demonstrates JWT authentication and can be used to verify that your
 * access token is working correctly.
 */

/**
 * Send a hello request with a name
 *
 * @param {string} name - Name to include in greeting (1-100 characters, printable only)
 * @returns {Promise<Object>} Greeting message response
 * @throws {Error} If name is invalid or authentication fails
 *
 * Response format:
 * {
 *   message: string  // e.g., "Hello, Alice! Welcome to MaplePress Backend."
 * }
 */
async function hello(name) {
  // Validate input
  if (!name || typeof name !== "string") {
    throw new Error("Name is required");
  }

  const trimmedName = name.trim();

  if (trimmedName.length === 0) {
    throw new Error("Name cannot be empty");
  }

  if (trimmedName.length > 100) {
    throw new Error("Name must be 100 characters or less");
  }

  // Basic validation for printable characters (no HTML tags)
  if (/<[^>]*>/.test(trimmedName)) {
    throw new Error("Name cannot contain HTML tags");
  }

  // Prepare request body (snake_case for backend)
  const requestBody = {
    name: trimmedName,
  };

  try {
    // Make API request (authenticated)
    const response = await ApiClient.post("/api/v1/hello", requestBody);

    // Response is already in the correct format (message field)
    return {
      message: response.message,
    };
  } 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("name")) {
      throw new Error("Invalid name provided. Please check your input.");
    }

    // Generic error
    throw new Error(
      error.message || "Failed to send hello request. Please try again."
    );
  }
}

/**
 * Validate a name before sending (client-side validation)
 *
 * @param {string} name - Name to validate
 * @returns {Object} { valid: boolean, error: string|null }
 */
function validateName(name) {
  if (!name || typeof name !== "string") {
    return { valid: false, error: "Name is required" };
  }

  const trimmedName = name.trim();

  if (trimmedName.length === 0) {
    return { valid: false, error: "Name cannot be empty" };
  }

  if (trimmedName.length > 100) {
    return { valid: false, error: "Name must be 100 characters or less" };
  }

  // Check for HTML tags
  if (/<[^>]*>/.test(trimmedName)) {
    return { valid: false, error: "Name cannot contain HTML tags" };
  }

  // Check for non-printable characters
  // eslint-disable-next-line no-control-regex
  if (/[\x00-\x1F\x7F-\x9F]/.test(trimmedName)) {
    return { valid: false, error: "Name contains invalid characters" };
  }

  return { valid: true, error: null };
}

// Export service
const HelloService = {
  hello,
  validateName,
};

export default HelloService;
