"use server";

import prisma from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { revalidatePath } from "next/cache";

/**
 * Create a new job alert from a saved search or from scratch.
 */
export async function createJobAlert(data: {
    name: string;
    filters: Record<string, any>;
    frequency: "instant" | "daily" | "weekly";
    minMatchScore?: number;
    maxResultsPerAlert?: number;
}) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        const alert = await prisma.savedSearch.create({
            data: {
                user_id: user.id,
                name: data.name,
                filters: data.filters,
                alert_frequency: data.frequency,
                min_match_score: data.minMatchScore ?? 70,
                max_results_per_alert: data.maxResultsPerAlert ?? 10,
                is_active: true,
            }
        });

        revalidatePath("/dashboard/settings");
        revalidatePath("/dashboard/saved");
        return { success: true, alertId: alert.id };
    } catch (error: any) {
        console.error("Failed to create job alert:", error);
        return { success: false, error: "Failed to create alert" };
    }
}

/**
 * Update an existing job alert's criteria, frequency, or controls.
 */
export async function updateJobAlert(alertId: string, data: {
    name?: string;
    filters?: Record<string, any>;
    frequency?: string;
    minMatchScore?: number;
    maxResultsPerAlert?: number;
}) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        // Verify ownership
        const existing = await prisma.savedSearch.findFirst({
            where: { id: alertId, user_id: user.id }
        });
        if (!existing) return { success: false, error: "Alert not found" };

        await prisma.savedSearch.update({
            where: { id: alertId },
            data: {
                ...(data.name && { name: data.name }),
                ...(data.filters && { filters: data.filters }),
                ...(data.frequency && { alert_frequency: data.frequency }),
                ...(data.minMatchScore !== undefined && { min_match_score: data.minMatchScore }),
                ...(data.maxResultsPerAlert !== undefined && { max_results_per_alert: data.maxResultsPerAlert }),
            }
        });

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

/**
 * Delete a job alert and its match history.
 */
export async function deleteJobAlert(alertId: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        const existing = await prisma.savedSearch.findFirst({
            where: { id: alertId, user_id: user.id }
        });
        if (!existing) return { success: false, error: "Alert not found" };

        await prisma.savedSearch.delete({ where: { id: alertId } });

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

/**
 * Pause a job alert temporarily (or indefinitely).
 */
export async function pauseJobAlert(alertId: string, until?: Date) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        await prisma.savedSearch.updateMany({
            where: { id: alertId, user_id: user.id },
            data: {
                is_active: false,
                paused_until: until || null,
            }
        });

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

/**
 * Resume a paused job alert.
 */
export async function resumeJobAlert(alertId: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        await prisma.savedSearch.updateMany({
            where: { id: alertId, user_id: user.id },
            data: {
                is_active: true,
                paused_until: null,
            }
        });

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

/**
 * Get all job alerts for the current user with match counts.
 */
export async function getJobAlerts() {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized", data: [] };

    try {
        const alerts = await prisma.savedSearch.findMany({
            where: { user_id: user.id, alert_frequency: { not: "none" } },
            include: {
                _count: {
                    select: {
                        matches: {
                            where: { emailed: true }
                        }
                    }
                }
            },
            orderBy: { updated_at: "desc" }
        });

        return { success: true, data: alerts };
    } catch (error: any) {
        console.error("Failed to fetch job alerts:", error);
        return { success: false, error: "Failed to fetch alerts", data: [] };
    }
}

/**
 * Convert an existing saved search into a job alert by setting a frequency.
 */
export async function enableAlertOnSavedSearch(savedSearchId: string, frequency: "instant" | "daily" | "weekly") {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        await prisma.savedSearch.updateMany({
            where: { id: savedSearchId, user_id: user.id },
            data: {
                alert_frequency: frequency,
                is_active: true,
            }
        });

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