import { v4 as uuidv4 } from 'uuid';

/**
 * External Mocks Service
 * Centralized place for mocking external dependencies until real APIs are ready.
 */
export const ExternalMocksService = {

    /**
     * Mock SAP Dealer Code Generation
     * Returns random codes for Sales, Service, GMA, and Gear.
     */
    mockGenerateSapCodes: async (applicationId: string) => {
        console.log(`[MOCK SAP] Generating codes for application: ${applicationId}`);
        // Simulate network delay
        await new Promise(resolve => setTimeout(resolve, 1000));

        return {
            success: true,
            data: {
                salesCode: `SLS-${Math.floor(1000 + Math.random() * 9000)}`,
                serviceCode: `SRV-${Math.floor(1000 + Math.random() * 9000)}`,
                gmaCode: `GMA-${Math.floor(1000 + Math.random() * 9000)}`,
                gearCode: `GER-${Math.floor(1000 + Math.random() * 9000)}`,
                sapMasterId: uuidv4().substring(0, 8).toUpperCase()
            }
        };
    },

    /**
     * Mock Gemini AI Summary Generation
     * Generates a consensus-based summary from panel feedback.
     */
    mockGenerateAiSummary: async (applicationId: string, feedbackList: any[]) => {
        console.log(`[MOCK GEMINI] Generating AI summary for: ${applicationId}`);
        await new Promise(resolve => setTimeout(resolve, 1500));

        const approveCount = feedbackList.filter(f => f.recommendation === 'Approve' || f.recommendation === 'Selected').length;
        const total = feedbackList.length;

        let summary = "";
        if (approveCount === total) {
            summary = "The panel has reached a strong consensus for approval. The candidate demonstrates exceptional business acumen and brand passion, with zero identified risks.";
        } else if (approveCount > total / 2) {
            summary = "The majority of the panel recommends approval, highlighting strong local market knowledge, though some concerns were raised regarding initial working capital which should be monitored.";
        } else {
            summary = "The panel is divided or leaning towards rejection. Concerns primarily focus on inadequate infrastructure readiness and limited previous experience in the automotive sector.";
        }

        return {
            success: true,
            summary
        };
    },

    /**
     * Mock Google Calendar Invite
     * Returns a mock meeting link.
     */
    mockScheduleMeeting: async (details: any) => {
        console.log(`[MOCK GOOGLE CALENDAR] Scheduling meeting: ${details.type} at ${details.scheduledAt}`);
        return {
            success: true,
            meetLink: `https://meet.google.com/mock-${uuidv4().substring(0, 8)}`,
            calendarEventId: uuidv4()
        };
    },

    /**
     * Mock WhatsApp Notification
     * Logs the notification instead of sending.
     */
    mockSendWhatsApp: async (phone: string, message: string) => {
        console.log(`[MOCK WHATSAPP] To: ${phone} | Message: ${message}`);
        // In a real implementation, sensitive docs would be excluded here per SRS.
        return {
            success: true,
            messageId: `WA-${uuidv4().substring(0, 12)}`
        };
    },

    /**
     * Mock SAP Status Synchronization
     * Simulates updating dealer status in SAP.
     */
    mockSyncDealerStatusToSap: async (dealerCode: string, status: string) => {
        console.log(`[MOCK SAP] Syncing status for dealer ${dealerCode}: ${status}`);
        await new Promise(resolve => setTimeout(resolve, 1200));
        return {
            success: true,
            sapTransactionId: `SAP-TX-${uuidv4().substring(0, 8).toUpperCase()}`,
            timestamp: new Date().toISOString()
        };
    },

    /**
     * Mock SAP financial data (ad-hoc tests / future real integration).
     * F&F settlement no longer auto-creates line items from this on initiate.
     */
    mockGetFinancialDuesFromSap: async (dealerCode: string) => {
        console.log(`[MOCK SAP] Fetching financial dues for dealer: ${dealerCode}`);
        await new Promise(resolve => setTimeout(resolve, 1500));
        return {
            success: true,
            data: {
                outstandingInvoices: Math.floor(50000 + Math.random() * 200000),
                securityDeposit: Math.floor(100000 + Math.random() * 500000),
                creditLimit: Math.floor(1000000 + Math.random() * 5000000),
                pendingClaims: Math.floor(10000 + Math.random() * 50000)
            }
        };
    }
};

export default ExternalMocksService;
