"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChatService = void 0;
const database_js_1 = require("../config/database.js");
class ChatService {
    static async getChatRooms(userId) {
        try {
            const chatRooms = await database_js_1.prisma.chatRoom.findMany({
                where: {
                    members: {
                        some: {
                            userId,
                        },
                    },
                },
                include: {
                    members: {
                        include: {
                            user: {
                                select: {
                                    id: true,
                                    username: true,
                                    isOnline: true,
                                    lastSeen: true,
                                    avatar: true,
                                },
                            },
                        },
                    },
                    _count: {
                        select: {
                            messages: true,
                        },
                    },
                },
                orderBy: {
                    updatedAt: "desc",
                },
            });
            return {
                success: true,
                data: chatRooms,
            };
        }
        catch (error) {
            console.error("Get chat rooms error:", error);
            return {
                success: false,
                error: "Failed to retrieve chat rooms",
            };
        }
    }
    static async createChatRoom(userId, data) {
        try {
            const chatRoom = await database_js_1.prisma.chatRoom.create({
                data: {
                    name: data.name,
                    description: data.description,
                    createdBy: userId,
                    members: {
                        create: [
                            {
                                userId,
                                role: "admin",
                            },
                        ],
                    },
                },
            });
            if (data.memberUsernames.length > 0) {
                const users = await database_js_1.prisma.user.findMany({
                    where: {
                        username: {
                            in: data.memberUsernames,
                        },
                    },
                });
                const memberData = users.map((user) => ({
                    userId: user.id,
                    roomId: chatRoom.id,
                }));
                await database_js_1.prisma.chatRoomMember.createMany({
                    data: memberData,
                    skipDuplicates: true,
                });
            }
            const fullChatRoom = await database_js_1.prisma.chatRoom.findUnique({
                where: { id: chatRoom.id },
                include: {
                    members: {
                        include: {
                            user: {
                                select: {
                                    id: true,
                                    username: true,
                                    isOnline: true,
                                    avatar: true,
                                },
                            },
                        },
                    },
                    _count: {
                        select: {
                            messages: true,
                        },
                    },
                },
            });
            return {
                success: true,
                data: fullChatRoom,
            };
        }
        catch (error) {
            console.error("Create chat room error:", error);
            return {
                success: false,
                error: "Failed to create chat room",
            };
        }
    }
    static async getMessages(query) {
        try {
            const page = Number.parseInt(query.page ?? "1");
            const limit = Number.parseInt(query.limit ?? "50");
            const skip = (page - 1) * limit;
            const messages = await database_js_1.prisma.message.findMany({
                where: {
                    roomId: query.roomId,
                },
                include: {
                    user: {
                        select: {
                            id: true,
                            username: true,
                            avatar: true,
                        },
                    },
                    reactions: {
                        include: {
                            user: {
                                select: {
                                    id: true,
                                    username: true,
                                },
                            },
                        },
                    },
                    seenBy: {
                        select: {
                            userId: true,
                        },
                    },
                },
                orderBy: {
                    createdAt: "desc",
                },
                take: limit,
                skip,
            });
            const formattedMessages = messages.map((message) => ({
                ...message,
                seenBy: message.seenBy.map((seen) => seen.userId),
            }));
            return {
                success: true,
                data: formattedMessages.reverse(),
            };
        }
        catch (error) {
            console.error("Get messages error:", error);
            return {
                success: false,
                error: "Failed to retrieve messages",
            };
        }
    }
    static async checkRoomMembership(userId, roomId) {
        try {
            const membership = await database_js_1.prisma.chatRoomMember.findUnique({
                where: {
                    userId_roomId: {
                        userId,
                        roomId,
                    },
                },
            });
            return !!membership;
        }
        catch (error) {
            console.error("Check room membership error:", error);
            return false;
        }
    }
    static async updateChatRoom(userId, roomId, data) {
        try {
            const membership = await database_js_1.prisma.chatRoomMember.findUnique({
                where: {
                    userId_roomId: {
                        userId,
                        roomId,
                    },
                },
            });
            if (!membership) {
                return {
                    success: false,
                    error: "You are not a member of this chat room",
                    status: 403,
                };
            }
            if (membership.role !== "admin") {
                return {
                    success: false,
                    error: "Only admins can update chat room settings",
                    status: 403,
                };
            }
            const updatedRoom = await database_js_1.prisma.chatRoom.update({
                where: { id: roomId },
                data: {
                    name: data.name,
                    description: data.description,
                    updatedAt: new Date(),
                },
                include: {
                    members: {
                        include: {
                            user: {
                                select: {
                                    id: true,
                                    username: true,
                                    isOnline: true,
                                    lastSeen: true,
                                    avatar: true,
                                },
                            },
                        },
                    },
                    _count: {
                        select: {
                            messages: true,
                        },
                    },
                },
            });
            return {
                success: true,
                data: updatedRoom,
            };
        }
        catch (error) {
            console.error("Update chat room error:", error);
            return {
                success: false,
                error: "Failed to update chat room",
                status: 500,
            };
        }
    }
    static async deleteChatRoom(userId, roomId) {
        try {
            const membership = await database_js_1.prisma.chatRoomMember.findUnique({
                where: {
                    userId_roomId: {
                        userId,
                        roomId,
                    },
                },
            });
            if (!membership) {
                return {
                    success: false,
                    error: "You are not a member of this chat room",
                    status: 403,
                };
            }
            if (membership.role !== "admin") {
                return {
                    success: false,
                    error: "Only admins can delete chat rooms",
                    status: 403,
                };
            }
            await database_js_1.prisma.chatRoom.delete({
                where: { id: roomId },
            });
            return {
                success: true,
                data: { id: roomId },
            };
        }
        catch (error) {
            console.error("Delete chat room error:", error);
            return {
                success: false,
                error: "Failed to delete chat room",
                status: 500,
            };
        }
    }
    static async addChatRoomMember(userId, roomId, data) {
        try {
            const membership = await database_js_1.prisma.chatRoomMember.findUnique({
                where: {
                    userId_roomId: {
                        userId,
                        roomId,
                    },
                },
            });
            if (!membership) {
                return {
                    success: false,
                    error: "You are not a member of this chat room",
                    status: 403,
                };
            }
            if (membership.role !== "admin") {
                return {
                    success: false,
                    error: "Only admins can add members",
                    status: 403,
                };
            }
            const user = await database_js_1.prisma.user.findUnique({
                where: { username: data.username },
            });
            if (!user) {
                return {
                    success: false,
                    error: "User not found",
                    status: 404,
                };
            }
            const existingMembership = await database_js_1.prisma.chatRoomMember.findUnique({
                where: {
                    userId_roomId: {
                        userId: user.id,
                        roomId,
                    },
                },
            });
            if (existingMembership) {
                return {
                    success: false,
                    error: "User is already a member of this chat room",
                    status: 409,
                };
            }
            await database_js_1.prisma.chatRoomMember.create({
                data: {
                    userId: user.id,
                    roomId,
                    role: "member",
                },
            });
            const updatedRoom = await database_js_1.prisma.chatRoom.findUnique({
                where: { id: roomId },
                include: {
                    members: {
                        include: {
                            user: {
                                select: {
                                    id: true,
                                    username: true,
                                    isOnline: true,
                                    lastSeen: true,
                                    avatar: true,
                                },
                            },
                        },
                    },
                    _count: {
                        select: {
                            messages: true,
                        },
                    },
                },
            });
            return {
                success: true,
                data: updatedRoom,
            };
        }
        catch (error) {
            console.error("Add chat room member error:", error);
            return {
                success: false,
                error: "Failed to add member to chat room",
                status: 500,
            };
        }
    }
    static async removeChatRoomMember(userId, roomId, data) {
        try {
            const membership = await database_js_1.prisma.chatRoomMember.findUnique({
                where: {
                    userId_roomId: {
                        userId,
                        roomId,
                    },
                },
            });
            if (!membership) {
                return {
                    success: false,
                    error: "You are not a member of this chat room",
                    status: 403,
                };
            }
            if (membership.role !== "admin") {
                return {
                    success: false,
                    error: "Only admins can remove members",
                    status: 403,
                };
            }
            // Check if target user is an admin
            const targetMembership = await database_js_1.prisma.chatRoomMember.findUnique({
                where: {
                    userId_roomId: {
                        userId: data.userId,
                        roomId,
                    },
                },
            });
            if (!targetMembership) {
                return {
                    success: false,
                    error: "User is not a member of this chat room",
                    status: 404,
                };
            }
            if (targetMembership.role === "admin") {
                return {
                    success: false,
                    error: "Cannot remove an admin from the chat room",
                    status: 403,
                };
            }
            // Remove user from chat room
            await database_js_1.prisma.chatRoomMember.delete({
                where: {
                    userId_roomId: {
                        userId: data.userId,
                        roomId,
                    },
                },
            });
            // Get updated chat room
            const updatedRoom = await database_js_1.prisma.chatRoom.findUnique({
                where: { id: roomId },
                include: {
                    members: {
                        include: {
                            user: {
                                select: {
                                    id: true,
                                    username: true,
                                    isOnline: true,
                                    lastSeen: true,
                                    avatar: true,
                                },
                            },
                        },
                    },
                    _count: {
                        select: {
                            messages: true,
                        },
                    },
                },
            });
            return {
                success: true,
                data: updatedRoom,
            };
        }
        catch (error) {
            console.error("Remove chat room member error:", error);
            return {
                success: false,
                error: "Failed to remove member from chat room",
                status: 500,
            };
        }
    }
}
exports.ChatService = ChatService;
