import { API_BASE_URL } from './config';

export interface ApiConfig {
  id: string;
  name: string;
  endpoint: string;
  apiKey: string;
  status: 'active' | 'inactive';
  timeout: number;
}

export interface SystemParameter {
  id: string;
  key: string;
  value: string;
  type: 'string' | 'number' | 'boolean' | 'json';
  description: string;
  category: string;
}

export interface Integration {
  id: string;
  name: string;
  type: string;
  status: 'connected' | 'disconnected' | 'error';
  config: Record<string, any>;
  lastSync: string;
}

export interface SecurityConfig {
  id: string;
  category: string;
  setting: string;
  value: boolean | string | number;
  description: string;
}

export interface AuditLog {
  id: string;
  action: string;
  user: string;
  timestamp: string;
  details: string;
  ip: string;
  status: 'success' | 'failed';
}

export interface PaymentConfig {
  id: string;
  provider: 'stripe' | 'paypal' | 'mercadopago' | 'bank_transfer';
  name: string;
  enabled: boolean;
  credentials: {
    publishableKey?: string;
    secretKey?: string;
    clientId?: string;
    clientSecret?: string;
    webhookSecret?: string;
    [key: string]: string | undefined;
  };
  status: 'active' | 'inactive' | 'testing';
  testMode: boolean;
  lastTested?: string;
}

export const configApi = {
  // API Configuration
  async getApiConfigs(): Promise<ApiConfig[]> {
    try {
      const response = await fetch(`${API_BASE_URL}/config/apis`);
      if (!response.ok) throw new Error('Failed to fetch API configs');
      return await response.json();
    } catch (error) {
      console.error('Error fetching API configs:', error);
      return [];
    }
  },

  async updateApiConfig(config: Partial<ApiConfig>): Promise<ApiConfig> {
    const response = await fetch(`${API_BASE_URL}/config/apis/${config.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(config),
    });
    if (!response.ok) throw new Error('Failed to update API config');
    return await response.json();
  },

  async testApiConnection(configId: string): Promise<boolean> {
    const response = await fetch(`${API_BASE_URL}/config/apis/${configId}/test`, {
      method: 'POST',
    });
    return response.ok;
  },

  // System Parameters
  async getSystemParameters(): Promise<SystemParameter[]> {
    try {
      const response = await fetch(`${API_BASE_URL}/config/parameters`);
      if (!response.ok) throw new Error('Failed to fetch system parameters');
      return await response.json();
    } catch (error) {
      console.error('Error fetching system parameters:', error);
      return [];
    }
  },

  async updateSystemParameter(parameter: Partial<SystemParameter>): Promise<SystemParameter> {
    const response = await fetch(`${API_BASE_URL}/config/parameters/${parameter.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(parameter),
    });
    if (!response.ok) throw new Error('Failed to update system parameter');
    return await response.json();
  },

  // Integrations
  async getIntegrations(): Promise<Integration[]> {
    try {
      const response = await fetch(`${API_BASE_URL}/config/integrations`);
      if (!response.ok) throw new Error('Failed to fetch integrations');
      return await response.json();
    } catch (error) {
      console.error('Error fetching integrations:', error);
      return [];
    }
  },

  async syncIntegration(integrationId: string): Promise<void> {
    const response = await fetch(`${API_BASE_URL}/config/integrations/${integrationId}/sync`, {
      method: 'POST',
    });
    if (!response.ok) throw new Error('Failed to sync integration');
  },

  async updateIntegration(integration: Partial<Integration>): Promise<Integration> {
    const response = await fetch(`${API_BASE_URL}/config/integrations/${integration.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(integration),
    });
    if (!response.ok) throw new Error('Failed to update integration');
    return await response.json();
  },

  // Security Configuration
  async getSecurityConfig(): Promise<SecurityConfig[]> {
    try {
      const response = await fetch(`${API_BASE_URL}/config/security`);
      if (!response.ok) throw new Error('Failed to fetch security config');
      return await response.json();
    } catch (error) {
      console.error('Error fetching security config:', error);
      return [];
    }
  },

  async updateSecurityConfig(config: Partial<SecurityConfig>): Promise<SecurityConfig> {
    const response = await fetch(`${API_BASE_URL}/config/security/${config.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(config),
    });
    if (!response.ok) throw new Error('Failed to update security config');
    return await response.json();
  },

  // Audit Logs
  async getAuditLogs(page = 1, limit = 50): Promise<{ logs: AuditLog[], total: number }> {
    try {
      const response = await fetch(`${API_BASE_URL}/config/audit-logs?page=${page}&limit=${limit}`);
      if (!response.ok) throw new Error('Failed to fetch audit logs');
      return await response.json();
    } catch (error) {
      console.error('Error fetching audit logs:', error);
      return { logs: [], total: 0 };
    }
  },

  // Payment Configuration
  async getPaymentConfigs(): Promise<PaymentConfig[]> {
    try {
      const response = await fetch(`${API_BASE_URL}/config/payments`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
          'Content-Type': 'application/json',
        },
      });
      if (!response.ok) {
        // Si el backend no responde, retornar configuraciones mock
        return this.getMockPaymentConfigs();
      }
      return await response.json();
    } catch (error) {
      console.error('Error fetching payment configs:', error);
      // Retornar configuraciones mock para desarrollo
      return this.getMockPaymentConfigs();
    }
  },

  getMockPaymentConfigs(): PaymentConfig[] {
    return [
      {
        id: 'stripe-1',
        provider: 'stripe',
        name: 'Stripe Payment Gateway',
        enabled: false,
        credentials: {
          publishableKey: '',
          secretKey: '',
          webhookSecret: '',
        },
        status: 'inactive',
        testMode: true,
      },
      {
        id: 'paypal-1',
        provider: 'paypal',
        name: 'PayPal Payment Gateway',
        enabled: false,
        credentials: {
          clientId: '',
          clientSecret: '',
        },
        status: 'inactive',
        testMode: true,
      },
    ];
  },

  async updatePaymentConfig(config: Partial<PaymentConfig>): Promise<PaymentConfig> {
    const response = await fetch(`${API_BASE_URL}/config/payments/${config.id}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(config),
    });
    if (!response.ok) throw new Error('Failed to update payment config');
    return await response.json();
  },

  async testPaymentConnection(configId: string): Promise<boolean> {
    const response = await fetch(`${API_BASE_URL}/config/payments/${configId}/test`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
        'Content-Type': 'application/json',
      },
    });
    return response.ok;
  },
};