"use server";

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

// ─── Types (preserved for backward compatibility with UI components) ───
export type ConversationFilter = "all" | "unread" | "starred" | "archived";
export type ConversationSort = "recent" | "unread_first" | "starred_first" | "alphabetical";

export interface ConversationSummary {
    applicationId: string;
    conversationId: string;
    jobTitle: string;
    jobId: string;
    otherUser: {
        id: string;
        name: string;
        role: string;
        avatar_url: string | null;
        company?: string;
        headline?: string;
    };
    lastMessage: {
        content: string;
        senderId: string;
        createdAt: string;
        isRead: boolean;
    };
    unreadCount: number;
    totalMessages: number;
    isStarred: boolean;
    isArchived: boolean;
    applicationStatus: string;
    updatedAt: string;
}

// ─── Get Conversations (now from Conversation model) ───
export async function getConversations(
    filter: ConversationFilter = "all",
    search: string = "",
    sort: ConversationSort = "recent"
): Promise<ConversationSummary[]> {
    const user = await getCurrentUser();
    if (!user) return [];

    const isEmployer = user.role === "employer";

    try {
        // Query from new Conversation model via participant memberships
        const memberships = await prisma.conversationParticipant.findMany({
            where: {
                user_id: user.id,
                left_at: null,
                conversation: {
                    status: filter === "archived" ? "archived" : "active",
                },
            },
            include: {
                conversation: {
                    include: {
                        participants: {
                            where: { left_at: null },
                            include: {
                                user: {
                                    select: {
                                        id: true,
                                        name: true,
                                        avatar_url: true,
                                        role: true,
                                        profile: {
                                            select: {
                                                headline: true,
                                                company_name: true,
                                            },
                                        },
                                    },
                                },
                            },
                        },
                        application: {
                            select: {
                                id: true,
                                status: true,
                                job: {
                                    select: {
                                        id: true,
                                        title: true,
                                        employer_id: true,
                                    },
                                },
                            },
                        },
                        messages: {
                            orderBy: { created_at: "desc" },
                            take: 1,
                            select: {
                                id: true,
                                content: true,
                                sender_id: true,
                                created_at: true,
                                is_deleted: true,
                            },
                        },
                        _count: {
                            select: { messages: true },
                        },
                    },
                },
            },
            orderBy: {
                conversation: { last_message_at: "desc" },
            },
        });

        // Build conversation summaries matching the legacy interface
        let conversations: ConversationSummary[] = memberships.map((m) => {
            const conv = m.conversation;
            const lastMsg = conv.messages[0];
            const otherParticipant = conv.participants.find(
                (p) => p.user_id !== user.id
            );
            const otherUser = otherParticipant?.user;

            // Determine if the last message was read by checking the membership's last_read_at
            const isLastMsgRead = lastMsg
                ? m.last_read_at
                    ? m.last_read_at >= lastMsg.created_at
                    : lastMsg.sender_id === user.id
                : true;

            return {
                applicationId: conv.application_id || conv.id,
                conversationId: conv.id,
                jobTitle: conv.application?.job?.title || conv.title || "Direct Message",
                jobId: conv.application?.job?.id || "",
                otherUser: {
                    id: otherUser?.id || "",
                    name: otherUser?.name || "Unknown",
                    role: otherUser?.role || "candidate",
                    avatar_url: otherUser?.avatar_url || null,
                    company: (otherUser as any)?.profile?.company_name || undefined,
                    headline: (otherUser as any)?.profile?.headline || undefined,
                },
                lastMessage: {
                    content: lastMsg
                        ? lastMsg.is_deleted
                            ? "[Message deleted]"
                            : lastMsg.content
                        : "",
                    senderId: lastMsg?.sender_id || "",
                    createdAt: lastMsg?.created_at?.toISOString() || "",
                    isRead: isLastMsgRead,
                },
                unreadCount: m.unread_count,
                totalMessages: conv._count.messages,
                isStarred: m.is_pinned, // Map "pinned" to "starred" for legacy UI
                isArchived: conv.status === "archived",
                applicationStatus: conv.application?.status || "active",
                updatedAt: conv.updated_at.toISOString(),
            };
        });

        // Apply filters
        switch (filter) {
            case "unread":
                conversations = conversations.filter((c) => c.unreadCount > 0);
                break;
            case "starred":
                conversations = conversations.filter((c) => c.isStarred);
                break;
            case "archived":
                // already filtered by status above
                break;
            case "all":
            default:
                conversations = conversations.filter((c) => !c.isArchived);
                break;
        }

        // Apply search
        if (search.trim()) {
            const q = search.toLowerCase();
            conversations = conversations.filter(
                (c) =>
                    c.otherUser.name.toLowerCase().includes(q) ||
                    c.jobTitle.toLowerCase().includes(q) ||
                    c.lastMessage.content.toLowerCase().includes(q) ||
                    (c.otherUser.company || "").toLowerCase().includes(q)
            );
        }

        // Apply sorting
        switch (sort) {
            case "unread_first":
                conversations.sort(
                    (a, b) =>
                        b.unreadCount - a.unreadCount ||
                        new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
                );
                break;
            case "starred_first":
                conversations.sort(
                    (a, b) =>
                        (b.isStarred ? 1 : 0) - (a.isStarred ? 1 : 0) ||
                        new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
                );
                break;
            case "alphabetical":
                conversations.sort((a, b) =>
                    a.otherUser.name.localeCompare(b.otherUser.name)
                );
                break;
            case "recent":
            default:
                // already sorted by last_message_at desc
                break;
        }

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

// ─── Get Unread Count (for nav badge) ───
export async function getUnreadMessageCount(): Promise<number> {
    const user = await getCurrentUser();
    if (!user) return 0;

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

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

// ─── Star / Unstar Conversation (uses pinned as star proxy) ───
export async function toggleConversationStar(
    applicationId: string
): Promise<{ success: boolean }> {
    const user = await getCurrentUser();
    if (!user) return { success: false };

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

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

        if (!conversation) return { success: false };

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

        if (!membership) return { success: false };

        await prisma.conversationParticipant.update({
            where: { id: membership.id },
            data: { is_pinned: !membership.is_pinned },
        });

        revalidatePath("/dashboard/messages");
        return { success: true };
    } catch (error) {
        console.error("Failed to toggle star:", error);
        return { success: false };
    }
}

// ─── Archive / Unarchive Conversation ───
export async function toggleConversationArchive(
    applicationId: string
): Promise<{ success: boolean }> {
    const user = await getCurrentUser();
    if (!user) return { success: false };

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

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

        if (!conversation) return { success: false };

        await prisma.conversation.update({
            where: { id: conversation.id },
            data: {
                status: conversation.status === "archived" ? "active" : "archived",
            },
        });

        revalidatePath("/dashboard/messages");
        return { success: true };
    } catch (error) {
        console.error("Failed to toggle archive:", error);
        return { success: false };
    }
}

// ─── Search Messages Globally ───
export async function searchMessages(query: string) {
    const user = await getCurrentUser();
    if (!user) return [];

    if (!query.trim()) return [];

    try {
        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, mode: "insensitive" },
            },
            include: {
                sender: { select: { name: true, avatar_url: true } },
                conversation: {
                    select: {
                        id: true,
                        title: true,
                        application: {
                            select: {
                                id: true,
                                job: { select: { title: true } },
                                candidate: { select: { name: true } },
                            },
                        },
                    },
                },
            },
            orderBy: { created_at: "desc" },
            take: 20,
        });

        return messages.map((msg) => ({
            id: msg.id,
            applicationId: msg.conversation.application?.id || msg.conversation_id,
            conversationId: msg.conversation_id,
            content: msg.content,
            senderName: msg.sender.name || "Unknown",
            jobTitle: msg.conversation.application?.job?.title || msg.conversation.title || "Direct Message",
            candidateName: msg.conversation.application?.candidate?.name || "Unknown",
            createdAt: msg.created_at.toISOString(),
        }));
    } catch (error) {
        console.error("Failed to search messages:", error);
        return [];
    }
}

// ─── Get Conversation Thread ───
export async function getConversationThread(applicationId: string) {
    const user = await getCurrentUser();
    if (!user) throw new Error("Unauthorized");

    try {
        // Look up conversation by applicationId first, then by conversationId
        let conversation = await prisma.conversation.findUnique({
            where: { application_id: applicationId },
        });

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

        if (!conversation) throw new Error("Conversation not found");

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

        if (!membership || membership.left_at) {
            throw new Error("Unauthorized");
        }

        // Load full data
        const fullConversation = await prisma.conversation.findUnique({
            where: { id: conversation.id },
            include: {
                participants: {
                    where: { left_at: null },
                    include: {
                        user: {
                            select: {
                                id: true,
                                name: true,
                                avatar_url: true,
                                email: true,
                                role: true,
                                profile: {
                                    select: {
                                        headline: true,
                                        company_name: true,
                                        location: true,
                                        phone: true,
                                    },
                                },
                            },
                        },
                    },
                },
                application: {
                    select: {
                        id: true,
                        status: true,
                        job: {
                            select: {
                                id: true,
                                title: true,
                                employer_id: true,
                            },
                        },
                        interviews: {
                            where: { status: "scheduled" },
                            orderBy: { scheduled_start_datetime: "asc" },
                            take: 1,
                        },
                    },
                },
                messages: {
                    orderBy: { created_at: "asc" },
                    include: {
                        sender: {
                            select: {
                                id: true,
                                name: true,
                                avatar_url: true,
                                role: true,
                            },
                        },
                        attachments: true,
                        reactions: {
                            include: {
                                user: {
                                    select: { id: true, name: true },
                                },
                            },
                        },
                    },
                },
            },
        });

        if (!fullConversation) throw new Error("Conversation not found");

        // Mark all unread messages as read
        const now = new Date();
        const unreadMsgs = fullConversation.messages.filter(
            (m) => m.sender_id !== user.id
        );

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

        // Reset unread count
        await prisma.conversationParticipant.update({
            where: { id: membership.id },
            data: {
                unread_count: 0,
                last_read_at: now,
                last_read_message_id: unreadMsgs.length > 0
                    ? unreadMsgs[unreadMsgs.length - 1].id
                    : undefined,
            },
        });

        // Find the "other user" for UI rendering
        const otherParticipant = fullConversation.participants.find(
            (p) => p.user_id !== user.id
        );
        const otherUser = otherParticipant?.user;

        return {
            applicationId: fullConversation.application?.id || fullConversation.id,
            conversationId: fullConversation.id,
            applicationStatus: fullConversation.application?.status || "active",
            jobTitle: fullConversation.application?.job?.title || fullConversation.title || "Direct Message",
            jobId: fullConversation.application?.job?.id || "",
            currentUserId: user.id,
            otherUser: {
                id: otherUser?.id || "",
                name: otherUser?.name || "Unknown",
                role: otherUser?.role || "candidate",
                avatar_url: otherUser?.avatar_url || null,
                email: otherUser?.email,
                headline: (otherUser as any)?.profile?.headline,
                company: (otherUser as any)?.profile?.company_name,
                location: (otherUser as any)?.profile?.location,
                phone: (otherUser as any)?.profile?.phone,
            },
            upcomingInterview: fullConversation.application?.interviews?.[0] || null,
            messages: fullConversation.messages.map((msg) => ({
                id: msg.id,
                content: msg.is_deleted ? "[Message deleted]" : msg.content,
                messageType: msg.message_type,
                attachmentUrl: msg.attachments?.[0]?.file_url || null,
                attachments: msg.attachments.map((a) => ({
                    id: a.id,
                    filename: a.filename,
                    fileUrl: a.file_url,
                    fileSize: a.file_size,
                    mimeType: a.mime_type,
                    thumbnailUrl: a.thumbnail_url,
                })),
                senderId: msg.sender_id,
                senderName: msg.sender.name || "Unknown",
                senderAvatar: msg.sender.avatar_url,
                senderRole: msg.sender.role,
                isRead: true, // All just marked as read
                isEdited: msg.is_edited,
                isDeleted: msg.is_deleted,
                reactions: msg.reactions.map((r) => ({
                    id: r.id,
                    reaction: r.reaction,
                    userId: r.user_id,
                    userName: r.user.name,
                })),
                createdAt: msg.created_at.toISOString(),
            })),
        };
    } catch (error) {
        console.error("Failed to get conversation thread:", error);
        throw error;
    }
}

// ─── Send Message (using new Message model) ───
export async function sendApplicationMessage(
    applicationId: string,
    content: string,
    messageType: string = "text"
) {
    const user = await getCurrentUser();
    if (!user) throw new Error("Unauthorized");
    if (!content.trim()) throw new Error("Message cannot be empty.");

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

        if (!conversation) {
            // If applicationId is actually a conversationId
            conversation = await prisma.conversation.findUnique({
                where: { id: applicationId },
            });
        }

        if (!conversation) {
            // Auto-create a conversation for 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) throw new Error("Application not found");

            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 the message and update conversation metadata atomically
        const [message] = await prisma.$transaction([
            prisma.message.create({
                data: {
                    conversation_id: conversation.id,
                    sender_id: user.id,
                    content: content.trim(),
                    message_type: messageType,
                },
                include: {
                    sender: {
                        select: {
                            id: true,
                            name: true,
                            avatar_url: true,
                            role: true,
                        },
                    },
                },
            }),
            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 },
                },
            }),
        ]);

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

        return {
            id: message.id,
            content: message.content,
            messageType: message.message_type,
            senderId: message.sender_id,
            senderName: message.sender.name || "Unknown",
            senderAvatar: message.sender.avatar_url,
            senderRole: message.sender.role,
            isRead: false,
            createdAt: message.created_at.toISOString(),
        };
    } catch (error) {
        console.error("Failed to send message:", error);
        throw error;
    }
}
