import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class WhatsappService {
    private logger = new Logger(WhatsappService.name);

    constructor(private prisma: PrismaService) { }

    private formatPhoneNumber(to: string): string {
        let mobile = to.replace(/\s/g, '').trim();
        // Handle common formats
        if (mobile.startsWith('whatsapp:')) {
            mobile = mobile.replace('whatsapp:', '');
        }
        if (mobile.startsWith('+')) {
            return mobile;
        }
        if (mobile.length === 10) {
            return `+91${mobile}`;
        }
        // If it starts with 91 but no plus
        if (mobile.length === 12 && mobile.startsWith('91')) {
            return `+${mobile}`;
        }
        return mobile;
    }

    async sendGreeting(to: string, clientName: string) {
        return this.sendTemplateMessage(to, 'GREETING', [clientName]);
    }

    async sendQuote(to: string, clientName: string, amount: string, mediaUrl?: string) {
        // Fallback for mock mode if URL is not configured
        if (!process.env.WHATSAPP_API_URL) {
            this.logger.warn('WHATSAPP_API_URL missing. Running in MOCK MODE.');
            this.logger.log(`[MOCK] Would send to ${to}: Quote for ${clientName} - Amount: ${amount} with media: ${mediaUrl}`);
            return { success: true, sid: 'mock_sid_' + Date.now() };
        }

        // Templates usually have placeholders. We'll map existing body to fields.
        return this.sendTemplateMessage(to, 'QUOTE', [clientName, amount], mediaUrl);
    }

    async sendNudge(to: string, clientName: string, stage: string) {
        return this.sendTemplateMessage(to, 'NUDGE', [clientName, stage]);
    }

    async sendTemplateMessage(to: string, type: string, fields: string[], headimg: string = "") {
        const template = await this.prisma.whatsappTemplate.findUnique({
            where: { type }
        });

        if (!template) {
            this.logger.error(`No WhatsApp template found for type: ${type}. Please register it in the whatsapp_template table.`);
            // For now, let's return a simulated success to avoid breaking the flow if templates aren't seeded
            return { success: false, error: `Template not found: ${type}` };
        }

        const mobile = this.formatPhoneNumber(to).replace('+', ''); // Many APIs don't want the +
        const url = process.env.WHATSAPP_API_URL;
        const cid = process.env.WHATSAPP_CID;

        if (!url) {
            throw new Error('WHATSAPP_API_URL is not configured in .env');
        }

        const payload = {
            custid: cid,
            template: template.templateName,
            ln: template.language,
            mn: mobile,
            category: 'utility', // Gateway expects 'category' not 'cat'
            fields: fields.join('|'),
            type: 'whatsapp',
            headimg: headimg || ""
        };

        let finalHeadImg = headimg || "";
        // If headimg is a local IP, the public gateway won't be able to fetch it.
        // For testing, we substitute it with a public dummy PDF.
        if (finalHeadImg.includes('192.168.') || finalHeadImg.includes('localhost') || finalHeadImg.includes('127.0.0.1')) {
            const dummyPdf = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
            this.logger.warn(`Local PDF detected (${finalHeadImg}). Substituting with public dummy PDF for testing: ${dummyPdf}`);
            finalHeadImg = dummyPdf;
        }

        const formData = new FormData();
        Object.entries(payload).forEach(([key, value]) => {
            if (key === 'headimg') {
                formData.append(key, finalHeadImg);
            } else {
                formData.append(key, value || "");
            }
        });

        try {
            this.logger.log(`Attempting to send WhatsApp via POST: ${url}`);
            this.logger.log(`Payload: ${JSON.stringify(payload)}`);

            const response = await fetch(url, {
                method: 'POST',
                body: formData
            });

            const resultText = await response.text();

            // Log the attempt
            await this.prisma.whatsappLog.create({
                data: {
                    recipient: mobile,
                    templateName: template.templateName,
                    payload: JSON.stringify(payload),
                    response: resultText,
                    status: response.ok ? 'SENT' : 'FAILED'
                }
            });

            if (!response.ok) {
                throw new Error(`External API returned ${response.status}: ${resultText}`);
            }

            this.logger.log(`WhatsApp ${type} sent to ${to}. Result: ${resultText}`);
            return { success: true, result: resultText };
        } catch (error) {
            this.logger.error(`Failed to send WhatsApp ${type}: ${error.message}`);

            // Log failure
            try {
                await this.prisma.whatsappLog.create({
                    data: {
                        recipient: mobile,
                        templateName: template.templateName,
                        payload: JSON.stringify(payload),
                        response: error.message,
                        status: 'ERROR'
                    }
                });
            } catch (logError) {
                this.logger.error(`Failed to log WhatsApp error: ${logError.message}`);
            }

            throw error;
        }
    }

    async sendOnboarding(to: string, clientName: string, memberId: string) {
        return this.sendTemplateMessage(to, 'ONBOARDING', [clientName, memberId]);
    }

    async sendFollowupReminder(to: string, clientName: string, date: string) {
        return this.sendTemplateMessage(to, 'FOLLOWUP', [clientName, date]);
    }

    async sendPipelineUpdate(to: string, clientName: string, oldStage: string, newStage: string) {
        return this.sendTemplateMessage(to, 'PIPELINE_UPDATE', [clientName, oldStage, newStage]);
    }

    async sendQuoteCreation(to: string, clientName: string, amount: string, pdfUrl?: string) {
        return this.sendTemplateMessage(to, 'QUOTE', [clientName, amount], pdfUrl);
    }

    async upsertTemplate(data: { type: string, templateName: string, language?: string, body?: string }) {
        return this.prisma.whatsappTemplate.upsert({
            where: { type: data.type },
            update: data,
            create: {
                type: data.type,
                templateName: data.templateName,
                language: data.language || 'en',
                body: data.body
            }
        });
    }
}
