"use server";

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

// ═══════════════════════════════════════════════
// CONVERSATIONS — CRUD
// ═══════════════════════════════════════════════

/**
 * Get all conversations for the current user, ordered by most recent.
 */
export async function getConversations(filters?: {
    status?: "active" | "archived";
    search?: string;
    type?: "direct" | "group" | "application";
}) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized", conversations: [] };

    try {
        const whereClause: any = {
            conversation: {
                status: filters?.status || "active",
                ...(filters?.type && { type: filters.type }),
            },
            user_id: user.id,
            left_at: null, // Still active in conversation
        };

        const memberships = await prisma.conversationParticipant.findMany({
            where: whereClause,
            include: {
                conversation: {
                    include: {
                        participants: {
                            include: {
                                user: {
                                    select: {
                                        id: true,
                                        name: true,
                                        first_name: true,
                                        last_name: true,
                                        avatar_url: true,
                                        role: true,
                                    },
                                },
                            },
                            where: { left_at: null },
                        },
                        application: {
                            select: {
                                id: true,
                                job: {
                                    select: {
                                        id: true,
                                        title: true,
                                        company: true,
                                    },
                                },
                                candidate: {
                                    select: {
                                        id: true,
                                        name: true,
                                        avatar_url: true,
                                    },
                                },
                            },
                        },
                    },
                },
            },
            orderBy: {
                conversation: {
                    last_message_at: "desc",
                },
            },
        });

        // Optional: filter by search
        let conversations = memberships.map((m) => ({
            ...m.conversation,
            myMembership: {
                id: m.id,
                is_muted: m.is_muted,
                is_pinned: m.is_pinned,
                unread_count: m.unread_count,
                last_read_at: m.last_read_at,
                role: m.role,
            },
        }));

        if (filters?.search) {
            const q = filters.search.toLowerCase();
            conversations = conversations.filter((c) => {
                // Search in title, participant names, last message preview
                if (c.title?.toLowerCase().includes(q)) return true;
                if (c.last_message_preview?.toLowerCase().includes(q)) return true;
                if (
                    c.participants.some((p) =>
                        p.user.name?.toLowerCase().includes(q)
                    )
                )
                    return true;
                return false;
            });
        }

        // Sort: pinned first, then by last_message_at
        conversations.sort((a, b) => {
            if (a.myMembership.is_pinned && !b.myMembership.is_pinned) return -1;
            if (!a.myMembership.is_pinned && b.myMembership.is_pinned) return 1;
            const aTime = a.last_message_at?.getTime() || 0;
            const bTime = b.last_message_at?.getTime() || 0;
            return bTime - aTime;
        });

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

/**
 * Get or create a conversation for an application (employer ↔ candidate).
 */
export async function getOrCreateApplicationConversation(applicationId: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        // Check access
        const application = await prisma.application.findUnique({
            where: { id: applicationId },
            include: {
                job: { select: { employer_id: true, title: true, company: true } },
                candidate: { select: { id: true, name: true } },
            },
        });

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

        // RBAC: only employer or candidate can access
        const isEmployer = user.id === application.job.employer_id;
        const isCandidate = user.id === application.candidate_id;
        if (!isEmployer && !isCandidate && user.role !== "admin") {
            return { success: false, error: "Unauthorized" };
        }

        // Check if conversation already exists
        let conversation = await prisma.conversation.findUnique({
            where: { application_id: applicationId },
            include: {
                participants: {
                    include: {
                        user: {
                            select: { id: true, name: true, avatar_url: true, role: true },
                        },
                    },
                },
            },
        });

        if (!conversation) {
            // Create conversation with both participants
            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",
                            },
                        ],
                    },
                },
                include: {
                    participants: {
                        include: {
                            user: {
                                select: { id: true, name: true, avatar_url: true, role: true },
                            },
                        },
                    },
                },
            });
        }

        return { success: true, conversation };
    } catch (error) {
        console.error("Failed to get/create conversation:", error);
        return { success: false, error: "Failed to access conversation." };
    }
}

/**
 * Create a new direct conversation between two users.
 */
export async function createDirectConversation(targetUserId: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };
    if (user.id === targetUserId)
        return { success: false, error: "Cannot message yourself." };

    try {
        // Check if a direct conversation already exists between these two users
        const existingMembership = await prisma.conversationParticipant.findFirst({
            where: {
                user_id: user.id,
                conversation: {
                    type: "direct",
                    participants: {
                        some: { user_id: targetUserId, left_at: null },
                    },
                },
                left_at: null,
            },
            include: {
                conversation: {
                    include: {
                        participants: {
                            include: {
                                user: {
                                    select: { id: true, name: true, avatar_url: true, role: true },
                                },
                            },
                        },
                    },
                },
            },
        });

        if (existingMembership) {
            return { success: true, conversation: existingMembership.conversation };
        }

        // Verify target user exists
        const targetUser = await prisma.user.findUnique({
            where: { id: targetUserId },
            select: { id: true, name: true },
        });
        if (!targetUser) {
            return { success: false, error: "User not found." };
        }

        const conversation = await prisma.conversation.create({
            data: {
                type: "direct",
                created_by: user.id,
                status: "active",
                participants: {
                    create: [
                        { user_id: user.id, role: "creator" },
                        { user_id: targetUserId, role: "member" },
                    ],
                },
            },
            include: {
                participants: {
                    include: {
                        user: {
                            select: { id: true, name: true, avatar_url: true, role: true },
                        },
                    },
                },
            },
        });

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

// ═══════════════════════════════════════════════
// MESSAGES — CRUD
// ═══════════════════════════════════════════════

/**
 * Get paginated messages for a conversation (cursor-based pagination).
 */
export async function getMessages(
    conversationId: string,
    cursor?: string, // message ID to paginate from
    limit: number = 50,
) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized", messages: [] };

    try {
        // Verify user is a participant
        const membership = await prisma.conversationParticipant.findUnique({
            where: {
                conversation_id_user_id: {
                    conversation_id: conversationId,
                    user_id: user.id,
                },
            },
        });

        if (!membership || membership.left_at) {
            return { success: false, error: "Not a member of this conversation.", messages: [] };
        }

        const messages = await prisma.message.findMany({
            where: { conversation_id: conversationId },
            take: limit,
            ...(cursor && {
                cursor: { id: cursor },
                skip: 1, // Skip the cursor message itself
            }),
            orderBy: { created_at: "desc" },
            include: {
                sender: {
                    select: {
                        id: true,
                        name: true,
                        first_name: true,
                        last_name: true,
                        avatar_url: true,
                        role: true,
                    },
                },
                reply_to: {
                    select: {
                        id: true,
                        content: true,
                        sender: {
                            select: { id: true, name: true },
                        },
                    },
                },
                attachments: true,
                reactions: {
                    include: {
                        user: {
                            select: { id: true, name: true },
                        },
                    },
                },
                read_receipts: {
                    include: {
                        user: {
                            select: { id: true, name: true, avatar_url: true },
                        },
                    },
                },
            },
        });

        const hasMore = messages.length === limit;
        const nextCursor = hasMore ? messages[messages.length - 1].id : null;

        return {
            success: true,
            messages: messages.reverse(), // Return in chronological order
            hasMore,
            nextCursor,
        };
    } catch (error) {
        console.error("Failed to fetch messages:", error);
        return { success: false, error: "Failed to load messages.", messages: [] };
    }
}

/**
 * Send a message in a conversation.
 */
export async function sendMessage(
    conversationId: string,
    content: string,
    options?: {
        replyToId?: string;
        messageType?: string;
        metadata?: Record<string, any>;
    }
) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };
    if (!content.trim()) return { success: false, error: "Message cannot be empty." };

    try {
        // Verify membership
        const membership = await prisma.conversationParticipant.findUnique({
            where: {
                conversation_id_user_id: {
                    conversation_id: conversationId,
                    user_id: user.id,
                },
            },
        });

        if (!membership || membership.left_at) {
            return { success: false, error: "Not a member of this conversation." };
        }

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

        // Create message + update conversation denormalized fields + increment unread counts
        const [message] = await prisma.$transaction([
            prisma.message.create({
                data: {
                    conversation_id: conversationId,
                    sender_id: user.id,
                    content: content.trim(),
                    message_type: options?.messageType || "text",
                    reply_to_id: options?.replyToId || null,
                    metadata: options?.metadata || undefined,
                },
                include: {
                    sender: {
                        select: {
                            id: true,
                            name: true,
                            avatar_url: true,
                            role: true,
                        },
                    },
                    reply_to: {
                        select: {
                            id: true,
                            content: true,
                            sender: { select: { id: true, name: true } },
                        },
                    },
                },
            }),
            // Update conversation last message
            prisma.conversation.update({
                where: { id: conversationId },
                data: {
                    last_message_at: now,
                    last_message_preview: preview,
                },
            }),
            // Increment unread count for all OTHER participants
            prisma.conversationParticipant.updateMany({
                where: {
                    conversation_id: conversationId,
                    user_id: { not: user.id },
                    left_at: null,
                },
                data: {
                    unread_count: { increment: 1 },
                },
            }),
        ]);

        revalidatePath("/dashboard/messages");
        revalidatePath(`/dashboard/messages/${conversationId}`);

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

/**
 * Edit a message (by the sender only).
 */
export async function editMessage(messageId: string, newContent: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };
    if (!newContent.trim()) return { success: false, error: "Content cannot be empty." };

    try {
        const message = await prisma.message.findUnique({
            where: { id: messageId },
            select: { sender_id: true, conversation_id: true },
        });

        if (!message) return { success: false, error: "Message not found." };
        if (message.sender_id !== user.id) return { success: false, error: "Can only edit your own messages." };

        const updated = await prisma.message.update({
            where: { id: messageId },
            data: {
                content: newContent.trim(),
                is_edited: true,
                edited_at: new Date(),
            },
        });

        // Update conversation preview if this was the last message
        await prisma.conversation.updateMany({
            where: {
                id: message.conversation_id,
                last_message_preview: { not: null }, // Only update if it's the latest
            },
            data: {
                last_message_preview: newContent.trim().substring(0, 200),
            },
        });

        revalidatePath(`/dashboard/messages/${message.conversation_id}`);

        return { success: true, message: updated };
    } catch (error) {
        console.error("Failed to edit message:", error);
        return { success: false, error: "Failed to edit message." };
    }
}

/**
 * Soft-delete a message. Content replaced with "[Message deleted]" for users.
 */
export async function deleteMessage(messageId: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        const message = await prisma.message.findUnique({
            where: { id: messageId },
            select: { sender_id: true, conversation_id: true },
        });

        if (!message) return { success: false, error: "Message not found." };
        const isAdmin = ["super_admin", "admin", "moderator", "analyst", "support"].includes(user.role);
        if (message.sender_id !== user.id && !isAdmin) {
            return { success: false, error: "Can only delete your own messages." };
        }

        await prisma.message.update({
            where: { id: messageId },
            data: {
                is_deleted: true,
                deleted_at: new Date(),
                deleted_by: user.id,
            },
        });

        revalidatePath(`/dashboard/messages/${message.conversation_id}`);

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

// ═══════════════════════════════════════════════
// READ RECEIPTS
// ═══════════════════════════════════════════════

/**
 * Mark all messages as read in a conversation up to the latest message.
 */
export async function markConversationRead(conversationId: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        const now = new Date();

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

        if (unreadMessages.length > 0) {
            // Create read receipts for all unread messages
            await prisma.messageReadReceipt.createMany({
                data: unreadMessages.map((msg) => ({
                    message_id: msg.id,
                    user_id: user.id,
                    read_at: now,
                })),
                skipDuplicates: true,
            });
        }

        // Reset unread count for this user
        await prisma.conversationParticipant.update({
            where: {
                conversation_id_user_id: {
                    conversation_id: conversationId,
                    user_id: user.id,
                },
            },
            data: {
                unread_count: 0,
                last_read_at: now,
                last_read_message_id: unreadMessages.length > 0
                    ? unreadMessages[unreadMessages.length - 1].id
                    : undefined,
            },
        });

        revalidatePath("/dashboard/messages");

        return { success: true };
    } catch (error) {
        console.error("Failed to mark as read:", error);
        return { success: false, error: "Failed to mark as read." };
    }
}

/**
 * Get total unread message count across all conversations.
 */
export async function getTotalUnreadCount() {
    const user = await getCurrentUser();
    if (!user) return { success: false, count: 0 };

    try {
        const result = await prisma.conversationParticipant.aggregate({
            where: {
                user_id: user.id,
                left_at: null,
                conversation: { status: "active" },
            },
            _sum: { unread_count: true },
        });

        return { success: true, count: result._sum.unread_count || 0 };
    } catch (error) {
        console.error("Failed to get unread count:", error);
        return { success: false, count: 0 };
    }
}

// ═══════════════════════════════════════════════
// REACTIONS
// ═══════════════════════════════════════════════

/**
 * Toggle a reaction on a message.
 */
export async function toggleReaction(messageId: string, reaction: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        // Verify the message exists and user has access
        const message = await prisma.message.findUnique({
            where: { id: messageId },
            select: { conversation_id: true },
        });

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

        const membership = await prisma.conversationParticipant.findUnique({
            where: {
                conversation_id_user_id: {
                    conversation_id: message.conversation_id,
                    user_id: user.id,
                },
            },
        });

        if (!membership || membership.left_at) {
            return { success: false, error: "Not a member of this conversation." };
        }

        // Check if reaction already exists
        const existing = await prisma.messageReaction.findUnique({
            where: {
                message_id_user_id_reaction: {
                    message_id: messageId,
                    user_id: user.id,
                    reaction,
                },
            },
        });

        if (existing) {
            // Remove reaction
            await prisma.messageReaction.delete({
                where: { id: existing.id },
            });
            return { success: true, action: "removed" };
        } else {
            // Add reaction
            await prisma.messageReaction.create({
                data: {
                    message_id: messageId,
                    user_id: user.id,
                    reaction,
                },
            });
            return { success: true, action: "added" };
        }
    } catch (error) {
        console.error("Failed to toggle reaction:", error);
        return { success: false, error: "Failed to react." };
    }
}

// ═══════════════════════════════════════════════
// CONVERSATION SETTINGS
// ═══════════════════════════════════════════════

/**
 * Toggle mute/pin/archive for a conversation.
 */
export async function updateConversationSettings(
    conversationId: string,
    settings: {
        is_muted?: boolean;
        is_pinned?: boolean;
        archive?: boolean;
    }
) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        if (settings.archive !== undefined) {
            // Archive/unarchive: update conversation status
            await prisma.conversation.update({
                where: { id: conversationId },
                data: {
                    status: settings.archive ? "archived" : "active",
                },
            });
        }

        // Update participant settings
        const updateData: any = {};
        if (settings.is_muted !== undefined) updateData.is_muted = settings.is_muted;
        if (settings.is_pinned !== undefined) updateData.is_pinned = settings.is_pinned;

        if (Object.keys(updateData).length > 0) {
            await prisma.conversationParticipant.update({
                where: {
                    conversation_id_user_id: {
                        conversation_id: conversationId,
                        user_id: user.id,
                    },
                },
                data: updateData,
            });
        }

        revalidatePath("/dashboard/messages");

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

/**
 * Search messages across all conversations.
 */
export async function searchMessages(query: string, limit: number = 20) {
    const user = await getCurrentUser();
    if (!user) return { success: false, messages: [] };

    if (!query.trim() || query.trim().length < 2) {
        return { success: false, error: "Query too short.", messages: [] };
    }

    try {
        // Get all conversation IDs the user is part of
        const memberships = await prisma.conversationParticipant.findMany({
            where: { user_id: user.id, left_at: null },
            select: { conversation_id: true },
        });

        const conversationIds = memberships.map((m) => m.conversation_id);

        const messages = await prisma.message.findMany({
            where: {
                conversation_id: { in: conversationIds },
                is_deleted: false,
                content: { contains: query.trim(), mode: "insensitive" },
            },
            take: limit,
            orderBy: { created_at: "desc" },
            include: {
                sender: {
                    select: { id: true, name: true, avatar_url: true },
                },
                conversation: {
                    select: {
                        id: true,
                        title: true,
                        type: true,
                    },
                },
            },
        });

        return { success: true, messages };
    } catch (error) {
        console.error("Failed to search messages:", error);
        return { success: false, error: "Search failed.", messages: [] };
    }
}
