/**
 * Integration API Service
 * Handles all integration-related API calls
 */
import { fetchAPI } from './api';

export interface SiteIntegration {
  id: number;
  site: number;
  platform: 'wordpress' | 'shopify' | 'custom';
  platform_type: 'cms' | 'ecommerce' | 'custom_api';
  config_json: Record<string, any>;
  credentials_json?: Record<string, any>;
  api_key?: string; // WordPress API key from credentials
  is_active: boolean;
  sync_enabled: boolean;
  last_sync_at?: string;
  sync_status: 'success' | 'failed' | 'pending';
  created_at: string;
  updated_at: string;
}

export interface CreateIntegrationData {
  site: number;
  platform: 'wordpress' | 'shopify' | 'custom';
  platform_type?: 'cms' | 'ecommerce' | 'custom_api';
  config_json: Record<string, any>;
  credentials_json?: Record<string, string>;
  is_active?: boolean;
  sync_enabled?: boolean;
}

export const integrationApi = {
  /**
   * Get all integrations for a site
   */
  async getSiteIntegrations(siteId: number): Promise<SiteIntegration[]> {
    const response = await fetchAPI(`/v1/integration/integrations/?site=${siteId}`);
    return response?.results || response || [];
  },

  /**
   * Get integration by ID
   */
  async getIntegration(integrationId: number): Promise<SiteIntegration> {
    return await fetchAPI(`/v1/integration/integrations/${integrationId}/`);
  },

  /**
   * Create new integration
   */
  async createIntegration(data: CreateIntegrationData): Promise<SiteIntegration> {
    return await fetchAPI('/v1/integration/integrations/', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  /**
   * Update integration
   */
  async updateIntegration(
    integrationId: number,
    data: Partial<CreateIntegrationData>
  ): Promise<SiteIntegration> {
    return await fetchAPI(`/v1/integration/integrations/${integrationId}/`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    });
  },

  /**
   * Delete integration
   */
  async deleteIntegration(integrationId: number): Promise<void> {
    await fetchAPI(`/v1/integration/integrations/${integrationId}/`, {
      method: 'DELETE',
    });
  },

  /**
   * Test integration connection
   */
  async testIntegration(integrationId: number): Promise<{ success: boolean; message: string }> {
    return await fetchAPI(`/v1/integration/integrations/${integrationId}/test/`, {
      method: 'POST',
    });
  },

  /**
   * Sync content from integration
   */
  async syncIntegration(
    integrationId: number,
    syncType: 'metadata' | 'incremental' | 'full' = 'metadata'
  ): Promise<{ success: boolean; message: string; post_types?: any; taxonomies?: any; last_sync_at?: string }> {
    return await fetchAPI(`/v1/integration/integrations/${integrationId}/sync/`, {
      method: 'POST',
      body: JSON.stringify({ 
        direction: syncType === 'metadata' ? 'metadata' : 'both'
      }),
    });
  },

  /**
   * Get WordPress integration for a site
   */
  async getWordPressIntegration(siteId: number): Promise<SiteIntegration | null> {
    const integrations = await this.getSiteIntegrations(siteId);
    return integrations.find((i) => i.platform === 'wordpress') || null;
  },

  /**
   * Create or update WordPress integration
   */
  async saveWordPressIntegration(
    siteId: number,
    data: {
      url: string;
      username: string;
      app_password: string;
      api_key?: string;
      is_active?: boolean;
      sync_enabled?: boolean;
    }
  ): Promise<SiteIntegration> {
    const existing = await this.getWordPressIntegration(siteId);

    const credentials: Record<string, string> = {
      username: data.username,
      app_password: data.app_password,
    };
    
    // Include API key if provided
    if (data.api_key) {
      credentials.api_key = data.api_key;
    }

    const integrationData: CreateIntegrationData = {
      site: siteId,
      platform: 'wordpress',
      platform_type: 'cms',
      config_json: {
        site_url: data.url,
      },
      credentials_json: credentials,
      is_active: data.is_active ?? true,
      sync_enabled: data.sync_enabled ?? true,
    };

    if (existing) {
      return await this.updateIntegration(existing.id, integrationData);
    } else {
      return await this.createIntegration(integrationData);
    }
  },
};

