// frontend/src/api/services/settings.ts
/**
 * API service for Tenant Settings
 * Handles all HTTP requests for tenant operational configuration
 */

import { apiClient } from '../client/apiClient';
import type {
  TenantSettings,
  TenantSettingsUpdate,
  SettingsCategory,
  CategoryResetResponse,
} from '../types/settings';

export const settingsApi = {
  /**
   * Get all settings for a tenant
   */
 getSettings: async (tenantId: string): Promise<TenantSettings> => {
    try {
      console.log('🔍 Fetching settings for tenant:', tenantId);
      const response = await apiClient.get<TenantSettings>(`/tenants/${tenantId}/settings`);
      console.log('📊 Settings API response data:', response);
      
      // Validate the response data structure
      if (!response) {
        throw new Error('Settings response data is null or undefined');
      }
      
      if (!response.tenant_id) {
        throw new Error('Settings response missing tenant_id');
      }
      
      if (!response.procurement_settings) {
        throw new Error('Settings response missing procurement_settings');
      }
      
      console.log('✅ Settings data validation passed');
      return response;
    } catch (error) {
      console.error('❌ Error fetching settings:', error);
      console.error('Error details:', {
        message: (error as Error).message,
        stack: (error as Error).stack,
        tenantId
      });
      throw error;
    }
 },

  /**
   * Update tenant settings (partial update supported)
   */
  updateSettings: async (
    tenantId: string,
    updates: TenantSettingsUpdate
  ): Promise<TenantSettings> => {
    try {
      console.log('🔍 Updating settings for tenant:', tenantId, 'with updates:', updates);
      const response = await apiClient.put<TenantSettings>(`/tenants/${tenantId}/settings`, updates);
      console.log('📊 Settings update response:', response);
      
      if (!response) {
        throw new Error('Settings update response data is null or undefined');
      }
      
      return response;
    } catch (error) {
      console.error('❌ Error updating settings:', error);
      throw error;
    }
  },

  /**
   * Get settings for a specific category
   */
  getCategorySettings: async (
    tenantId: string,
    category: SettingsCategory
  ): Promise<Record<string, any>> => {
    try {
      console.log('🔍 Fetching category settings for tenant:', tenantId, 'category:', category);
      const response = await apiClient.get<{ tenant_id: string; category: string; settings: Record<string, any> }>(
        `/tenants/${tenantId}/settings/${category}`
      );
      console.log('📊 Category settings response:', response);
      
      if (!response || !response.settings) {
        throw new Error('Category settings response data is null or undefined');
      }
      
      return response.settings;
    } catch (error) {
      console.error('❌ Error fetching category settings:', error);
      throw error;
    }
  },

  /**
   * Update settings for a specific category
   */
  updateCategorySettings: async (
    tenantId: string,
    category: SettingsCategory,
    settings: Record<string, any>
  ): Promise<TenantSettings> => {
    try {
      console.log('🔍 Updating category settings for tenant:', tenantId, 'category:', category, 'settings:', settings);
      const response = await apiClient.put<TenantSettings>(
        `/tenants/${tenantId}/settings/${category}`,
        { settings }
      );
      console.log('📊 Category settings update response:', response);
      
      if (!response) {
        throw new Error('Category settings update response data is null or undefined');
      }
      
      return response;
    } catch (error) {
      console.error('❌ Error updating category settings:', error);
      throw error;
    }
  },

  /**
   * Reset a category to default values
   */
 resetCategory: async (
    tenantId: string,
    category: SettingsCategory
  ): Promise<CategoryResetResponse> => {
    try {
      console.log('🔍 Resetting category for tenant:', tenantId, 'category:', category);
      const response = await apiClient.post<CategoryResetResponse>(
        `/tenants/${tenantId}/settings/${category}/reset`
      );
      console.log('📊 Category reset response:', response);
      
      if (!response) {
        throw new Error('Category reset response data is null or undefined');
      }
      
      return response;
    } catch (error) {
      console.error('❌ Error resetting category:', error);
      throw error;
    }
  },
};

export default settingsApi;
