"use server";

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

// ─── Send Message (routed through new Conversation/Message system) ───
export async function sendApplicationMessage(
    applicationId: string,
    content: string,
    hasFiles = false
) {
    const user = await getCurrentUser();
    if (!user) {
        return { success: false, error: "Unauthorized" };
    }

    if (!content.trim()) {
        return { success: false, error: "Message cannot be empty" };
    }

    // Verify the user has access to this application
    const application = await prisma.application.findUnique({
        where: { id: applicationId },
        include: {
            job: { select: { employer_id: true, title: true } },
            candidate: { select: { id: true, name: true } },
        },
    });

    if (!application) {
        return { success: false, error: "Application not found" };
    }

    // RBAC: candidate can only message their own, employer only their jobs
    if (
        user.role === "candidate" &&
        application.candidate_id !== user.id
    ) {
        return { success: false, error: "Unauthorized" };
    }

    if (
        user.role === "employer" &&
        application.job.employer_id !== user.id
    ) {
        return { success: false, error: "Unauthorized" };
    }

    try {
        // Find or create conversation for this application
        let conversation = await prisma.conversation.findUnique({
            where: { application_id: applicationId },
        });

        if (!conversation) {
            conversation = await prisma.conversation.create({
                data: {
                    type: "application",
                    application_id: applicationId,
                    created_by: user.id,
                    title: `${application.job.title} — ${application.candidate.name}`,
                    status: "active",
                    participants: {
                        create: [
                            {
                                user_id: application.job.employer_id,
                                role: "creator",
                            },
                            {
                                user_id: application.candidate_id,
                                role: "member",
                            },
                        ],
                    },
                },
            });
        }

        const preview = content.trim().substring(0, 200);
        const now = new Date();

        // Create message in new system + update conversation denormalized fields
        const [message] = await prisma.$transaction([
            prisma.message.create({
                data: {
                    conversation_id: conversation.id,
                    sender_id: user.id,
                    content: content.trim(),
                    message_type: "text",
                },
            }),
            prisma.conversation.update({
                where: { id: conversation.id },
                data: {
                    last_message_at: now,
                    last_message_preview: preview,
                },
            }),
            prisma.conversationParticipant.updateMany({
                where: {
                    conversation_id: conversation.id,
                    user_id: { not: user.id },
                    left_at: null,
                },
                data: {
                    unread_count: { increment: 1 },
                },
            }),
        ]);

        // Log activity
        await prisma.applicationActivity.create({
            data: {
                application_id: applicationId,
                actor_id: user.id,
                action: "message_sent",
                details: {
                    preview: content.trim().substring(0, 80),
                    conversationId: conversation.id,
                    messageId: message.id,
                },
            },
        });

        // Fetch other participants to notify them
        const otherParticipants = await prisma.conversationParticipant.findMany({
            where: {
                conversation_id: conversation.id,
                user_id: { not: user.id },
                left_at: null,
            },
            include: {
                user: {
                    select: {
                        id: true,
                        name: true,
                        email: true,
                        notification_settings: {
                            where: { category: "messages" }
                        }
                    }
                }
            }
        });

        // Determine job title for the email
        const jobTitle = application?.job?.title || "a position";

        if (otherParticipants.length > 0) {
            // In-app notifications
            await prisma.notification.createMany({
                data: otherParticipants.map(p => ({
                    user_id: p.user_id,
                    type: "new_message",
                    title: `New message from ${user.name || "someone"}`,
                    message: content.trim().substring(0, 80) + (content.length > 80 ? "..." : ""),
                    link: `/dashboard/messages/${applicationId}`,
                }))
            });

            // Email notifications (fire & forget — don't block message send)
            for (const p of otherParticipants) {
                if (p.user?.email) {
                    // Check user's notification preferences for messages
                    const messageSettings = p.user.notification_settings?.[0];
                    // Default to instant email if no explicit setting exists
                    const shouldSendEmail = messageSettings ? messageSettings.email === "instant" : true;

                    if (shouldSendEmail) {
                        sendNewMessageNotificationEmail(
                            p.user.email,
                            p.user.name || "there",
                            user.name || "A user",
                            jobTitle,
                            content.trim().substring(0, 120),
                            applicationId
                        ).catch(err => console.error("Email notification failed:", err));
                    }
                }
            }
        }

        // ─── Push real-time event via internal API route ───
        // Server actions run in a separate bundle from API routes in Next.js,
        // so we call the push API route (which shares the SSE connection pool)
        // to deliver messages instantly.
        if (!hasFiles) {
            const baseUrl = process.env.NEXTAUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
            fetch(`${baseUrl}/api/messages/push`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "x-internal-secret": process.env.INTERNAL_API_SECRET || "internal-push-secret-key",
                },
                body: JSON.stringify({
                    conversationId: conversation.id,
                    event: {
                        type: "new_message",
                        data: {
                            id: message.id,
                            content: message.content,
                            messageType: message.message_type,
                            senderId: user.id,
                            senderName: user.name || "User",
                            senderAvatar: user.avatarUrl || null,
                            senderRole: user.role,
                            createdAt: message.created_at.toISOString(),
                            attachments: [],
                        },
                        timestamp: new Date().toISOString(),
                    },
                }),
            }).catch((err) => console.error("[Realtime] Push failed:", err));
        }

        revalidatePath(`/dashboard/messages/${applicationId}`);
        revalidatePath(`/dashboard/messages`);
        return {
            success: true,
            messageId: message.id,
            conversationId: conversation.id,
        };
    } catch (error) {
        console.error("Failed to send message:", error);
        return { success: false, error: "Internal error" };
    }
}

// ─── Broadcast Complete Message (After Uploads) ───
export async function broadcastCompleteMessage(messageId: string, conversationId: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        const message = await prisma.message.findUnique({
            where: { id: messageId },
            include: { attachments: true },
        });

        if (!message) return { success: false, error: "Not found" };

        const baseUrl = process.env.NEXTAUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
        await fetch(`${baseUrl}/api/messages/push`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "x-internal-secret": process.env.INTERNAL_API_SECRET || "internal-push-secret-key",
            },
            body: JSON.stringify({
                conversationId,
                event: {
                    type: "new_message",
                    data: {
                        id: message.id,
                        content: message.content,
                        messageType: message.message_type,
                        senderId: user.id,
                        senderName: user.name || "User",
                        senderAvatar: user.avatarUrl || null,
                        senderRole: user.role,
                        createdAt: message.created_at.toISOString(),
                        attachments: message.attachments.map(att => ({
                            id: att.id,
                            filename: att.filename,
                            fileUrl: att.file_url,
                            fileSize: att.file_size,
                            mimeType: att.mime_type,
                            thumbnailUrl: att.thumbnail_url,
                        })),
                    },
                    timestamp: new Date().toISOString(),
                },
            }),
        });

        return { success: true };
    } catch (error) {
        console.error("Failed to broadcast complete message:", error);
        return { success: false, error: "Internal error" };
    }
}

// ─── Mark Messages Read (using new ReadReceipt system) ───
export async function markMessagesRead(applicationId: string) {
    const user = await getCurrentUser();
    if (!user) return;

    try {
        // Find conversation
        let conversation = await prisma.conversation.findUnique({
            where: { application_id: applicationId },
        });

        if (!conversation) {
            conversation = await prisma.conversation.findUnique({
                where: { id: applicationId },
            });
        }

        if (!conversation) return;

        const now = new Date();

        // Get all unread messages from others
        const unreadMessages = await prisma.message.findMany({
            where: {
                conversation_id: conversation.id,
                sender_id: { not: user.id },
                read_receipts: {
                    none: { user_id: user.id },
                },
            },
            select: { id: true },
        });

        if (unreadMessages.length > 0) {
            await prisma.messageReadReceipt.createMany({
                data: unreadMessages.map((msg) => ({
                    message_id: msg.id,
                    user_id: user.id,
                    read_at: now,
                })),
                skipDuplicates: true,
            });
        }

        // Reset unread count
        await prisma.conversationParticipant.updateMany({
            where: {
                conversation_id: conversation.id,
                user_id: user.id,
            },
            data: {
                unread_count: 0,
                last_read_at: now,
            },
        });

        revalidatePath(`/dashboard/messages/${applicationId}`);
        revalidatePath(`/dashboard/messages`);
    } catch (error) {
        console.error("Failed to mark messages read:", error);
    }
}

// ─── Message Templates (unchanged — uses MessageTemplate model) ───

export type MessageTemplateCategory =
    | "interview_invite"
    | "status_update"
    | "rejection"
    | "offer"
    | "thank_you"
    | "follow_up"
    | "custom";

export interface MessageTemplateData {
    id: string;
    title: string;
    content: string;
    category: MessageTemplateCategory;
    is_default: boolean;
}

export async function getMessageTemplates(category?: MessageTemplateCategory) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return { success: false, templates: [] };
    }

    try {
        const whereClause: any = { user_id: user.id };
        if (category) {
            whereClause.category = category;
        }

        const templates = await prisma.messageTemplate.findMany({
            where: whereClause,
            orderBy: [{ is_default: 'desc' }, { created_at: 'desc' }],
        });

        return { success: true, templates: templates as MessageTemplateData[] };
    } catch (error) {
        console.error("Failed to fetch templates:", error);
        return { success: false, error: "Failed to fetch templates." };
    }
}

export async function createMessageTemplate(data: Omit<MessageTemplateData, 'id'>) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return { success: false, error: "Unauthorized" };
    }

    if (!data.title?.trim() || !data.content?.trim()) {
        return { success: false, error: "Title and content are required." };
    }

    try {
        // Find placeholders dynamically from content {bracket_format}
        const placeholders = Array.from(new Set(data.content.match(/\{[^}]+\}/g) || []));

        const template = await prisma.messageTemplate.create({
            data: {
                title: data.title.trim(),
                content: data.content.trim(),
                category: data.category,
                is_default: data.is_default || false,
                placeholders: placeholders,
                user_id: user.id,
            },
        });

        return { success: true, template };
    } catch (error) {
        console.error("Failed to create template:", error);
        return { success: false, error: "Failed to create template." };
    }
}

export async function deleteMessageTemplate(id: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return { success: false, error: "Unauthorized" };
    }

    try {
        // Ensure user owns this template
        const template = await prisma.messageTemplate.findUnique({
            where: { id },
            select: { user_id: true }
        });

        if (!template || template.user_id !== user.id) {
            return { success: false, error: "Template not found or unauthorized." };
        }

        await prisma.messageTemplate.delete({
            where: { id },
        });

        return { success: true };
    } catch (error) {
        console.error("Failed to delete template:", error);
        return { success: false, error: "Failed to delete template." };
    }
}
