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

/**
 * RegisterService
 *
 * Handles user registration API calls to the MaplePress backend.
 * Based on backend API: POST /api/v1/register
 */

import ApiClient from "./ApiClient.js";

/**
 * Register a new user and create a tenant
 *
 * @param {Object} data - Registration data
 * @param {string} data.email - User's email address
 * @param {string} data.password - User's password (min 8 characters)
 * @param {string} data.first_name - User's first name
 * @param {string} data.last_name - User's last name
 * @param {string} data.tenant_name - Organization/tenant name (slug auto-generated from this)
 * @param {string} [data.timezone] - User's timezone (defaults to "UTC")
 * @param {boolean} data.agree_terms_of_service - Must be true
 * @param {boolean} [data.agree_promotions] - Optional (default: false)
 * @param {boolean} [data.agree_to_tracking_across_third_party_apps_and_services] - Optional (default: false)
 *
 * @returns {Promise<Object>} Registration response with tokens
 * @throws {Error} Registration error with message
 */
async function register(data) {
  try {
    console.log("[RegisterService] Registering user:", data.email);

    // No frontend validation - all validation handled by backend
    // This allows backend to return ALL validation errors at once

    // Prepare request body matching backend RegisterRequest structure
    const requestBody = {
      email: data.email,
      password: data.password,
      confirm_password: data.confirmPassword,
      first_name: data.first_name,
      last_name: data.last_name,
      tenant_name: data.tenant_name,
      timezone: data.timezone || "UTC",
      agree_terms_of_service: data.agree_terms_of_service,
      agree_promotions: data.agree_promotions || false,
      agree_to_tracking_across_third_party_apps_and_services:
        data.agree_to_tracking_across_third_party_apps_and_services || false,
    };

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

    console.log("[RegisterService] Registration successful:", response.user_id);

    // Return response matching backend RegisterResponse 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,
      tenantName: response.tenant_name,
      tenantSlug: response.tenant_slug,

      // 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),

      createdAt: new Date(response.created_at),
    };
  } catch (error) {
    console.error("[RegisterService] Registration failed:", error);

    // Pass through the original error object to preserve RFC 9457 fields
    // (validationErrors, title, status, etc.) that ApiClient attached
    // The Register page component will parse and display field-specific errors
    throw error;
  }
}

const RegisterService = {
  register,
};

export default RegisterService;
