import http from '@/services/http';
import type { 
  CrmLead, 
  CrmTask, 
  CrmContact, 
  CrmDeal,
  CrmSearchParams,
  CrmApiResponse,
  CrmPaginatedResponse
} from '../types/CrmTypes';

// Available CRM resource types
export type CrmResourceType = 'leads' | 'tasks' | 'deals' | 'contacts' | 'sales-orders' | 'purchase-orders' | 'invoices';

// Base API endpoint
const CRM_BASE_URL = '/api/v1/integrations/data';

export const crmAPI = {
  // Generic method to get CRM data by resource type
  getCrmData: <T = any>(
    resource: CrmResourceType, 
    params?: CrmSearchParams
  ) => {
    const queryParams = {
      provider: 'zoho',
      service: 'crm',
      resource,
      page: params?.page || 1,
      limit: params?.limit || 20,
      ...params
    };
    
    return http.get<CrmApiResponse<CrmPaginatedResponse<T>>>(CRM_BASE_URL, queryParams);
  },

  // Specific resource methods for type safety
  getLeads: (params?: CrmSearchParams) => 
    crmAPI.getCrmData<CrmLead>('leads', params),
  
  getTasks: (params?: CrmSearchParams) => 
    crmAPI.getCrmData<CrmTask>('tasks', params),
  
  getContacts: (params?: CrmSearchParams) => 
    crmAPI.getCrmData<CrmContact>('contacts', params),
  
  getDeals: (params?: CrmSearchParams) => 
    crmAPI.getCrmData<CrmDeal>('deals', params),
  
  // New API endpoints for sales orders, purchase orders, and invoices
  getSalesOrders: (params?: CrmSearchParams) => {
    const queryParams = {
      provider: 'zoho',
      page: params?.page || 1,
      limit: params?.limit || 20,
      ...params
    };
    return http.get<CrmApiResponse<CrmPaginatedResponse<any>>>(`/api/v1/integrations/zoho/crm/sales-orders`, queryParams);
  },
  
  getPurchaseOrders: (params?: CrmSearchParams) => {
    const queryParams = {
      provider: 'zoho',
      page: params?.page || 1,
      limit: params?.limit || 20,
      ...params
    };
    return http.get<CrmApiResponse<CrmPaginatedResponse<any>>>(`/api/v1/integrations/zoho/crm/purchase-orders`, queryParams);
  },
  
  getInvoices: (params?: CrmSearchParams) => {
    const queryParams = {
      provider: 'zoho',
      page: params?.page || 1,
      limit: params?.limit || 20,
      ...params
    };
    return http.get<CrmApiResponse<CrmPaginatedResponse<any>>>(`/api/v1/integrations/zoho/crm/invoices`, queryParams);
  },

  // Get counts for all CRM modules
  getCrmCounts: () => {
    return http.get<{
      status: string;
      message: string;
      data: {
        data: {
          accounts: { count: number; success: boolean };
          leads: { count: number; success: boolean };
          tasks: { count: number; success: boolean };
          invoices: { count: number; success: boolean };
          sales_orders: { count: number; success: boolean };
          purchase_orders: { count: number; success: boolean };
          deals: { count: number; success: boolean };
          contacts: { count: number; success: boolean };
          vendors: { count: number; success: boolean };
        };
        info: {
          totalModules: number;
          successfulModules: number;
          failedModules: number;
        };
      };
      timestamp: string;
    }>('/api/v1/integrations/zoho/crm/counts', { provider: 'zoho' });
  },

  // Get comprehensive CRM KPIs report
  getCrmKPIs: () => {
    return http.get<{
      status: string;
      message: string;
      data: {
        businessOverview: {
          totalRecords: number;
          moduleCounts: {
            leads: number;
            contacts: number;
            accounts: number;
            deals: number;
            tasks: number;
            vendors: number;
            invoices: number;
            salesOrders: number;
            purchaseOrders: number;
          };
          revenueMetrics: {
            totalRevenue: number;
            totalDealValue: number;
            totalInvoices: number;
            averageInvoiceValue: number;
            overdueAmount: number;
            overdueCount: number;
            revenueByMonth: Array<{ month: string; revenue: number }>;
            topRevenueAccounts: Array<{ account: string; revenue: number }>;
          };
          growthMetrics: {
            recentLeads: number;
            previousLeads: number;
            recentDeals: number;
            previousDeals: number;
            leadGrowthRate: string;
            dealGrowthRate: string;
          };
        };
        salesPipeline: {
          totalLeads: number;
          totalDeals: number;
          qualifiedLeads: number;
          convertedLeads: number;
          openDeals: number;
          closedWonDeals: number;
          totalPipelineValue: number;
          conversionRate: string;
          qualificationRate: string;
          winRate: string;
          dealStages: Record<string, number>;
          leadSources: Record<string, number>;
          conversionFunnel: {
            leads: { count: number; percentage: number };
            qualified: { count: number; percentage: string };
            converted: { count: number; percentage: string };
            deals: { count: number; percentage: number };
            closedWon: { count: number; percentage: string };
          };
        };
        operationalEfficiency: {
          totalTasks: number;
          completedTasks: number;
          overdueTasks: number;
          highPriorityTasks: number;
          taskCompletionRate: string;
          overdueRate: string;
          taskStatus: Record<string, number>;
          invoiceStatus: Record<string, number>;
          orderStatus: {
            salesOrders: Record<string, number>;
            purchaseOrders: Record<string, number>;
          };
        };
        customerRelationships: {
          totalContacts: number;
          totalAccounts: number;
          totalVendors: number;
          recentContacts: number;
          accountsWithRevenue: number;
          contactToAccountRatio: string;
          industryDistribution: Record<string, number>;
          contactSources: Record<string, number>;
          accountOwnership: Record<string, number>;
        };
        financialHealth: {
          totalRevenue: number;
          totalInvoices: number;
          averageInvoiceValue: number;
          overdueAmount: number;
          revenueByMonth: Array<{ month: string; revenue: number }>;
          topRevenueAccounts: Array<{ account: string; revenue: number }>;
        };
        businessInsights: {
          topPerformingSources: Array<{
            source: string;
            totalLeads: number;
            qualifiedLeads: number;
            conversionRate: string;
            avgQuality: string;
          }>;
          topRevenueOwners: Array<{
            owner: string;
            count: number;
            total: number;
          }>;
          mostActiveOwners: Array<{
            owner: string;
            count: number;
            value: number;
          }>;
          businessHealth: {
            overallScore: number;
            leadGeneration: number;
            processEfficiency: number;
            qualityMetrics: number;
          };
          recommendations: Array<{
            category: string;
            priority: string;
            title: string;
            description: string;
            action: string;
          }>;
        };
        generatedAt: string;
        advancedFinancialKPIs: {
          revenueGrowthRate: { value: number; percentage: string; trend: string };
          grossMargin: { value: number; percentage: string; totalRevenue: number; totalCOGS: number; grossProfit: number };
          netProfitMargin: { value: number; percentage: string; totalRevenue: number; totalCosts: number; netProfit: number };
          operatingCashFlow: { cashIn: number; cashOut: number; netCashFlow: number; cashFlowRatio: string };
          cashRunway: { months: string; status: string; monthlyCashIn: number; monthlyCashOut: number };
          customerAcquisitionCost: { value: number; marketingSpend: number; newCustomers: number; status: string };
          customerLifetimeValue: { value: number; totalRevenue: number; totalCustomers: number; status: string };
          ltvToCacRatio: { ratio: string; status: string };
          netRevenueRetention: { percentage: string; recurringRevenue: number; currentCustomers: number; status: string };
          churnRate: { percentage: string; lostCustomers: number; totalCustomers: number; status: string };
          averageRevenuePerAccount: { value: number; totalRevenue: number; totalAccounts: number; status: string };
          burnMultiple: { multiple: string; totalBurn: number; newARR: number; status: string };
          salesCycleLength: { averageDays: number; status: string };
          netPromoterScore: { score: number; promoters: number; totalCustomers: number; status: string; note: string };
          daysSalesOutstanding: { days: number; totalOutstanding: number; averageDailySales: number; status: string };
          growthEfficiencyRatio: { ratio: string; status: string };
          ebitda: { value: number; totalRevenue: number; totalCosts: number; margin: string; status: string };
        };
      };
      timestamp: string;
    }>('/api/v1/reports/crm/kpis');
  },
};

