"use server";

import prisma from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { revalidatePath } from "next/cache";
import { EMAIL_CATEGORIES, REQUIRED_CATEGORIES } from "@/lib/email/constants";



/**
 * Get the full email preferences for a user (global prefs + per-category settings).
 */
export async function getEmailPreferences(userId?: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    const targetUserId = userId || user.id;

    // Admins can view anyone; others can only view their own
    if (targetUserId !== user.id && user.role !== 'admin') {
        return { success: false, error: "Forbidden" };
    }

    try {
        const [globalPrefs, categorySettings, jobAlerts] = await Promise.all([
            prisma.emailPreference.findUnique({ where: { user_id: targetUserId } }),
            prisma.notificationSetting.findMany({ where: { user_id: targetUserId } }),
            prisma.savedSearch.findMany({
                where: { user_id: targetUserId, alert_frequency: { not: "none" } },
                select: { id: true, name: true, alert_frequency: true, is_active: true, paused_until: true }
            })
        ]);

        const role = user.role as keyof typeof EMAIL_CATEGORIES;
        const categories = EMAIL_CATEGORIES[role] || EMAIL_CATEGORIES.candidate;

        return {
            success: true,
            data: {
                global: globalPrefs || {
                    unsubscribed_all: false,
                    global_pause_until: null,
                    quiet_hours_start: null,
                    quiet_hours_end: null,
                    digest_time: "09:00",
                    timezone: "Africa/Lagos"
                },
                categories: categories.map(cat => {
                    const setting = categorySettings.find(s => s.category === cat.id);
                    return {
                        ...cat,
                        enabled: setting ? setting.email !== 'off' : true,
                        frequency: setting?.email || 'instant',
                        in_app: setting?.in_app ?? true,
                        sms: setting?.sms ?? false,
                        push: setting?.push ?? false,
                        isRequired: REQUIRED_CATEGORIES.includes(cat.id),
                    };
                }),
                jobAlerts
            }
        };
    } catch (error: any) {
        console.error("Failed to fetch email preferences:", error);
        return { success: false, error: "Failed to fetch preferences" };
    }
}

/**
 * Update global email preferences (pause, quiet hours, timezone).
 */
export async function updateGlobalEmailPreferences(data: {
    globalPauseUntil?: Date | null;
    quietHoursStart?: string | null;
    quietHoursEnd?: string | null;
    digestTime?: string;
    timezone?: string;
    unsubscribedAll?: boolean;
}) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        await prisma.emailPreference.upsert({
            where: { user_id: user.id },
            create: {
                user_id: user.id,
                global_pause_until: data.globalPauseUntil,
                quiet_hours_start: data.quietHoursStart,
                quiet_hours_end: data.quietHoursEnd,
                digest_time: data.digestTime || '09:00',
                timezone: data.timezone || 'Africa/Lagos',
                unsubscribed_all: data.unsubscribedAll ?? false,
            },
            update: {
                ...(data.globalPauseUntil !== undefined && { global_pause_until: data.globalPauseUntil }),
                ...(data.quietHoursStart !== undefined && { quiet_hours_start: data.quietHoursStart }),
                ...(data.quietHoursEnd !== undefined && { quiet_hours_end: data.quietHoursEnd }),
                ...(data.digestTime && { digest_time: data.digestTime }),
                ...(data.timezone && { timezone: data.timezone }),
                ...(data.unsubscribedAll !== undefined && { unsubscribed_all: data.unsubscribedAll }),
            }
        });

        // If unsubscribing all, add to suppression
        if (data.unsubscribedAll === true) {
            await prisma.emailSuppression.upsert({
                where: { email: user.email },
                create: { email: user.email, reason: 'unsubscribe', is_permanent: false },
                update: { reason: 'unsubscribe', suppressed_at: new Date() }
            });
        } else if (data.unsubscribedAll === false) {
            // Remove from suppression if re-subscribing
            await prisma.emailSuppression.deleteMany({ where: { email: user.email, reason: 'unsubscribe' } });
        }

        revalidatePath("/dashboard/settings");
        return { success: true };
    } catch (error: any) {
        console.error("Failed to update global email preferences:", error);
        return { success: false, error: "Failed to update preferences" };
    }
}

/**
 * Update a single category's notification settings.
 */
export async function updateCategoryPreference(category: string, data: {
    email?: string; // 'off', 'instant', 'daily', 'weekly'
    inApp?: boolean;
    sms?: boolean;
    push?: boolean;
}) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    // Block disabling required categories
    if (REQUIRED_CATEGORIES.includes(category) && data.email === 'off') {
        return { success: false, error: "This category cannot be disabled" };
    }

    try {
        await prisma.notificationSetting.upsert({
            where: { user_id_category: { user_id: user.id, category } },
            create: {
                user_id: user.id,
                category,
                email: data.email || 'instant',
                in_app: data.inApp ?? true,
                sms: data.sms ?? false,
                push: data.push ?? false,
            },
            update: {
                ...(data.email !== undefined && { email: data.email }),
                ...(data.inApp !== undefined && { in_app: data.inApp }),
                ...(data.sms !== undefined && { sms: data.sms }),
                ...(data.push !== undefined && { push: data.push }),
            }
        });

        revalidatePath("/dashboard/settings");
        return { success: true };
    } catch (error: any) {
        console.error("Failed to update category preference:", error);
        return { success: false, error: "Failed to update preference" };
    }
}

/**
 * Unsubscribe from all emails (nuclear option).
 */
export async function unsubscribeFromAll() {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        await prisma.$transaction([
            // Set global unsubscribe flag
            prisma.emailPreference.upsert({
                where: { user_id: user.id },
                create: { user_id: user.id, unsubscribed_all: true },
                update: { unsubscribed_all: true }
            }),
            // Add to suppression
            prisma.emailSuppression.upsert({
                where: { email: user.email },
                create: { email: user.email, reason: 'unsubscribe', is_permanent: false },
                update: { reason: 'unsubscribe', suppressed_at: new Date() }
            }),
            // Pause all job alerts
            prisma.savedSearch.updateMany({
                where: { user_id: user.id, alert_frequency: { not: 'none' } },
                data: { is_active: false }
            })
        ]);

        revalidatePath("/dashboard/settings");
        return { success: true };
    } catch (error: any) {
        console.error("Failed to unsubscribe from all:", error);
        return { success: false, error: "Failed to unsubscribe" };
    }
}

/**
 * Re-subscribe (reverses global unsubscribe).
 */
export async function resubscribeAll() {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        await prisma.$transaction([
            prisma.emailPreference.upsert({
                where: { user_id: user.id },
                create: { user_id: user.id, unsubscribed_all: false },
                update: { unsubscribed_all: false }
            }),
            prisma.emailSuppression.deleteMany({
                where: { email: user.email, reason: 'unsubscribe' }
            })
        ]);

        revalidatePath("/dashboard/settings");
        return { success: true };
    } catch (error: any) {
        console.error("Failed to resubscribe:", error);
        return { success: false, error: "Failed to resubscribe" };
    }
}

/**
 * Pause all emails for a duration.
 */
export async function pauseAllEmails(until: Date) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        await prisma.emailPreference.upsert({
            where: { user_id: user.id },
            create: { user_id: user.id, global_pause_until: until },
            update: { global_pause_until: until }
        });

        revalidatePath("/dashboard/settings");
        return { success: true };
    } catch (error: any) {
        console.error("Failed to pause emails:", error);
        return { success: false, error: "Failed to pause emails" };
    }
}

/**
 * Resume all paused emails.
 */
export async function resumeAllEmails() {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        await prisma.emailPreference.upsert({
            where: { user_id: user.id },
            create: { user_id: user.id, global_pause_until: null },
            update: { global_pause_until: null }
        });

        revalidatePath("/dashboard/settings");
        return { success: true };
    } catch (error: any) {
        console.error("Failed to resume emails:", error);
        return { success: false, error: "Failed to resume emails" };
    }
}

/**
 * Fetch the user's recent email history (last 10 emails).
 */
export async function getRecentEmails() {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        const emails = await prisma.emailLog.findMany({
            where: { user_id: user.id },
            orderBy: { sent_at: 'desc' },
            take: 10,
            select: {
                id: true,
                type: true,
                to: true,
                status: true,
                delivery_status: true,
                sent_at: true,
            }
        });

        return { success: true, data: emails };
    } catch (error: any) {
        console.error("Failed to fetch recent emails:", error);
        return { success: false, error: "Failed to fetch emails" };
    }
}
