import prisma from "@/lib/prisma";

/**
 * EmailTrackingService
 * Handles delivery event recording, bounce classification, complaint handling,
 * and analytics aggregation for the email delivery tracking system.
 */
export class EmailTrackingService {

    /**
     * Record a delivery event for an email log entry.
     */
    static async recordEvent(
        emailLogId: string,
        eventType: string,
        metadata?: Record<string, any>
    ) {
        try {
            // Create the event record
            await prisma.emailEvent.create({
                data: {
                    email_log_id: emailLogId,
                    event_type: eventType,
                    metadata: metadata || {},
                }
            });

            // Update the email log based on event type
            const now = new Date();
            const updateData: Record<string, any> = {};

            switch (eventType) {
                case "delivered":
                    updateData.delivery_status = "delivered";
                    updateData.status = "DELIVERED";
                    updateData.delivered_at = now;
                    break;
                case "opened":
                    updateData.delivery_status = "opened";
                    updateData.status = "OPENED";
                    if (!updateData.opened_at) updateData.opened_at = now;
                    updateData.last_opened_at = now;
                    updateData.open_count = { increment: 1 };
                    if (metadata?.user_agent) updateData.user_agent = metadata.user_agent;
                    if (metadata?.ip) updateData.ip_address = metadata.ip;
                    break;
                case "clicked":
                    updateData.delivery_status = "clicked";
                    updateData.status = "CLICKED";
                    if (!updateData.clicked_at) updateData.clicked_at = now;
                    updateData.click_count = { increment: 1 };
                    if (metadata?.user_agent) updateData.user_agent = metadata.user_agent;
                    if (metadata?.ip) updateData.ip_address = metadata.ip;
                    break;
                case "bounced":
                    updateData.delivery_status = "bounced";
                    updateData.status = "BOUNCED";
                    updateData.bounced_at = now;
                    updateData.bounce_type = metadata?.bounce_type || "hard";
                    updateData.bounce_reason = metadata?.reason || "Unknown";
                    break;
                case "complained":
                    updateData.delivery_status = "complained";
                    updateData.status = "COMPLAINED";
                    updateData.complained_at = now;
                    break;
                case "unsubscribed":
                    // Don't change delivery status, just log the event
                    break;
            }

            if (Object.keys(updateData).length > 0) {
                await prisma.emailLog.update({
                    where: { id: emailLogId },
                    data: updateData,
                });
            }

            return { success: true };
        } catch (error) {
            console.error("[EmailTracking] Failed to record event:", error);
            return { success: false, error };
        }
    }

    /**
     * Handle a bounce event — classifies and auto-suppresses hard bounces.
     */
    static async handleBounce(emailLogId: string, bounceType: "hard" | "soft", reason: string) {
        const result = await this.recordEvent(emailLogId, "bounced", {
            bounce_type: bounceType,
            reason,
        });

        if (bounceType === "hard") {
            // Get the email address and add to suppression list
            const log = await prisma.emailLog.findUnique({
                where: { id: emailLogId },
                select: { to: true },
            });

            if (log) {
                await prisma.emailSuppression.upsert({
                    where: { email: log.to },
                    create: {
                        email: log.to,
                        reason: "hard_bounce",
                        is_permanent: true,
                    },
                    update: {
                        reason: "hard_bounce",
                        is_permanent: true,
                        suppressed_at: new Date(),
                    },
                });
                console.log(`[EmailTracking] Hard bounce: ${log.to} added to suppression list`);
            }
        }

        return result;
    }

    /**
     * Handle a spam complaint — immediately suppresses the email address.
     */
    static async handleComplaint(emailLogId: string) {
        const result = await this.recordEvent(emailLogId, "complained", {});

        const log = await prisma.emailLog.findUnique({
            where: { id: emailLogId },
            select: { to: true },
        });

        if (log) {
            await prisma.emailSuppression.upsert({
                where: { email: log.to },
                create: {
                    email: log.to,
                    reason: "spam_complaint",
                    is_permanent: true,
                },
                update: {
                    reason: "spam_complaint",
                    is_permanent: true,
                    suppressed_at: new Date(),
                },
            });
            console.log(`[EmailTracking] Spam complaint: ${log.to} permanently suppressed`);
        }

        return result;
    }

    /**
     * Get full event timeline for a specific email.
     */
    static async getEmailStatus(emailLogId: string) {
        return prisma.emailLog.findUnique({
            where: { id: emailLogId },
            include: {
                events: {
                    orderBy: { created_at: "asc" },
                },
            },
        });
    }

    /**
     * Get delivery analytics for the admin dashboard.
     */
    static async getDeliveryAnalytics(filters: {
        startDate?: Date;
        endDate?: Date;
        emailType?: string;
        status?: string;
    } = {}) {
        const { startDate, endDate, emailType, status } = filters;
        const where: Record<string, any> = {};

        if (startDate || endDate) {
            where.sent_at = {};
            if (startDate) where.sent_at.gte = startDate;
            if (endDate) where.sent_at.lte = endDate;
        }
        if (emailType && emailType !== "all") where.type = emailType;
        if (status && status !== "all") where.delivery_status = status;

        // Overview stats
        const [total, delivered, opened, clicked, bounced, complained, failed] = await Promise.all([
            prisma.emailLog.count({ where }),
            prisma.emailLog.count({ where: { ...where, delivery_status: { in: ["delivered", "opened", "clicked"] } } }),
            prisma.emailLog.count({ where: { ...where, open_count: { gt: 0 } } }),
            prisma.emailLog.count({ where: { ...where, click_count: { gt: 0 } } }),
            prisma.emailLog.count({ where: { ...where, delivery_status: "bounced" } }),
            prisma.emailLog.count({ where: { ...where, delivery_status: "complained" } }),
            prisma.emailLog.count({ where: { ...where, status: "FAILED" } }),
        ]);

        // Bounce breakdown
        const bounceBreakdown = await prisma.emailLog.groupBy({
            by: ["bounce_type"],
            where: { ...where, delivery_status: "bounced" },
            _count: true,
        });

        // By email type
        const byType = await prisma.emailLog.groupBy({
            by: ["type"],
            where,
            _count: true,
        });

        // Recent events
        const recentEvents = await prisma.emailEvent.findMany({
            where: where.sent_at ? {
                created_at: where.sent_at,
            } : {},
            include: {
                email_log: { select: { to: true, type: true, subject: true } },
            },
            orderBy: { created_at: "desc" },
            take: 20,
        });

        return {
            overview: {
                total,
                delivered,
                opened,
                clicked,
                bounced,
                complained,
                failed,
                deliveryRate: total > 0 ? ((delivered / total) * 100).toFixed(1) : "0",
                openRate: delivered > 0 ? ((opened / delivered) * 100).toFixed(1) : "0",
                clickRate: opened > 0 ? ((clicked / opened) * 100).toFixed(1) : "0",
                bounceRate: total > 0 ? ((bounced / total) * 100).toFixed(1) : "0",
                complaintRate: total > 0 ? ((complained / total) * 100).toFixed(2) : "0",
            },
            bounceBreakdown: bounceBreakdown.map(b => ({
                type: b.bounce_type || "unknown",
                count: b._count,
            })),
            byType: byType.map(t => ({
                type: t.type,
                count: t._count,
            })),
            recentEvents: recentEvents.map(e => ({
                id: e.id,
                eventType: e.event_type,
                email: e.email_log?.to,
                emailType: e.email_log?.type,
                subject: e.email_log?.subject,
                metadata: e.metadata,
                timestamp: e.created_at,
            })),
        };
    }

    /**
     * Get trend data for charts — daily aggregated stats.
     */
    static async getTrendData(days: number = 30, emailType?: string) {
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - days);

        const where: Record<string, any> = {
            date: { gte: startDate },
        };
        if (emailType && emailType !== "all") {
            where.email_type = emailType;
        } else {
            where.email_type = "all";
        }

        const stats = await prisma.emailDeliveryStats.findMany({
            where,
            orderBy: { date: "asc" },
        });

        return stats.map(s => ({
            date: s.date.toISOString().split("T")[0],
            sent: s.sent,
            delivered: s.delivered,
            opened: s.opened,
            clicked: s.clicked,
            bouncedHard: s.bounced_hard,
            bouncedSoft: s.bounced_soft,
            complained: s.complained,
            openRate: s.delivered > 0 ? Math.round((s.opened / s.delivered) * 100) : 0,
            clickRate: s.opened > 0 ? Math.round((s.clicked / s.opened) * 100) : 0,
        }));
    }

    /**
     * Aggregate daily stats — called by a cron job.
     */
    static async aggregateDailyStats(date?: Date) {
        const targetDate = date || new Date();
        targetDate.setHours(0, 0, 0, 0);

        const nextDate = new Date(targetDate);
        nextDate.setDate(nextDate.getDate() + 1);

        // Get all email types sent on this date
        const types = await prisma.emailLog.groupBy({
            by: ["type"],
            where: {
                sent_at: { gte: targetDate, lt: nextDate },
            },
        });

        const allTypes = [...types.map(t => t.type), "all"];

        for (const emailType of allTypes) {
            const typeWhere = emailType === "all"
                ? { sent_at: { gte: targetDate, lt: nextDate } }
                : { sent_at: { gte: targetDate, lt: nextDate }, type: emailType };

            const [sent, delivered, opened, clicked, bouncedHard, bouncedSoft, complained, failed, skipped] = await Promise.all([
                prisma.emailLog.count({ where: { ...typeWhere, status: { in: ["SENT", "DELIVERED", "OPENED", "CLICKED"] } } }),
                prisma.emailLog.count({ where: { ...typeWhere, delivery_status: { in: ["delivered", "opened", "clicked"] } } }),
                prisma.emailLog.count({ where: { ...typeWhere, open_count: { gt: 0 } } }),
                prisma.emailLog.count({ where: { ...typeWhere, click_count: { gt: 0 } } }),
                prisma.emailLog.count({ where: { ...typeWhere, bounce_type: "hard" } }),
                prisma.emailLog.count({ where: { ...typeWhere, bounce_type: "soft" } }),
                prisma.emailLog.count({ where: { ...typeWhere, delivery_status: "complained" } }),
                prisma.emailLog.count({ where: { ...typeWhere, status: "FAILED" } }),
                prisma.emailLog.count({ where: { ...typeWhere, status: "SKIPPED" } }),
            ]);

            // Get unsubscribe count from events
            const unsubscribed = await prisma.emailEvent.count({
                where: {
                    event_type: "unsubscribed",
                    created_at: { gte: targetDate, lt: nextDate },
                    ...(emailType !== "all" ? { email_log: { type: emailType } } : {}),
                },
            });

            await prisma.emailDeliveryStats.upsert({
                where: {
                    date_email_type: { date: targetDate, email_type: emailType },
                },
                create: {
                    date: targetDate,
                    email_type: emailType,
                    sent,
                    delivered,
                    opened,
                    clicked,
                    bounced_hard: bouncedHard,
                    bounced_soft: bouncedSoft,
                    complained,
                    unsubscribed,
                    failed,
                    skipped,
                },
                update: {
                    sent,
                    delivered,
                    opened,
                    clicked,
                    bounced_hard: bouncedHard,
                    bounced_soft: bouncedSoft,
                    complained,
                    unsubscribed,
                    failed,
                    skipped,
                },
            });
        }

        return { success: true, types: allTypes.length };
    }

    /**
     * Get dead letter queue (permanently failed emails).
     */
    static async getDeadLetterQueue(page = 1, limit = 20) {
        const [items, total] = await Promise.all([
            prisma.emailQueue.findMany({
                where: { status: "DEAD" },
                orderBy: { updated_at: "desc" },
                skip: (page - 1) * limit,
                take: limit,
            }),
            prisma.emailQueue.count({ where: { status: "DEAD" } }),
        ]);

        return { items, total, page, totalPages: Math.ceil(total / limit) };
    }

    /**
     * Retry a dead letter queue item.
     */
    static async retryDeadLetter(queueId: string) {
        await prisma.emailQueue.update({
            where: { id: queueId },
            data: {
                status: "PENDING",
                attempts: 0,
                last_error: null,
                scheduled_for: null,
            },
        });
        return { success: true };
    }

    /**
     * Delete a dead letter queue item.
     */
    static async deleteDeadLetter(queueId: string) {
        await prisma.emailQueue.delete({ where: { id: queueId } });
        return { success: true };
    }

    /**
     * Get user's recent email history with delivery status.
     */
    static async getUserEmailHistory(userId: string, limit = 10) {
        return prisma.emailLog.findMany({
            where: { user_id: userId },
            select: {
                id: true,
                type: true,
                subject: true,
                delivery_status: true,
                sent_at: true,
                delivered_at: true,
                opened_at: true,
                bounced_at: true,
                bounce_type: true,
                bounce_reason: true,
            },
            orderBy: { sent_at: "desc" },
            take: limit,
        });
    }
}
