import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";

export async function GET(request: Request) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const { searchParams } = new URL(request.url);
        const query = searchParams.get("q") || "";
        const limit = parseInt(searchParams.get("limit") || "20");
        const conversationId = searchParams.get("conversationId");

        if (!query.trim()) {
            return NextResponse.json({ results: [] });
        }

        // Fetch accessible conversations for the user
        let userConversations;

        if (conversationId) {
            // Verify user has access to this specific conversation
            const participant = await prisma.conversationParticipant.findUnique({
                where: {
                    conversation_id_user_id: {
                        conversation_id: conversationId,
                        user_id: currentUser.id
                    }
                }
            });
            if (!participant) {
                return NextResponse.json({ error: "Unauthorized access to conversation" }, { status: 403 });
            }
            userConversations = [conversationId];
        } else {
            // Get all conversations the user is part of
            const memberships = await prisma.conversationParticipant.findMany({
                where: { user_id: currentUser.id },
                select: { conversation_id: true }
            });
            userConversations = memberships.map(m => m.conversation_id);
        }

        if (userConversations.length === 0) {
            return NextResponse.json({ results: [] });
        }

        // Search messages containing the keyword
        const messages = await prisma.message.findMany({
            where: {
                conversation_id: { in: userConversations },
                content: {
                    contains: query,
                    mode: 'insensitive' // Requires PostgreSQL
                },
                is_deleted: false,
            },
            include: {
                conversation: {
                    select: {
                        id: true,
                        title: true,
                        application: {
                            select: {
                                job: { select: { title: true } },
                                candidate: { select: { name: true } },
                            }
                        }
                    }
                },
                sender: {
                    select: {
                        id: true,
                        name: true,
                        avatar_url: true,
                    }
                }
            },
            orderBy: {
                created_at: 'desc'
            },
            take: limit,
        });

        // Format results
        const formattedResults = messages.map(msg => ({
            id: msg.id,
            conversationId: msg.conversation_id,
            conversationTitle: msg.conversation.title
                || (msg.conversation.application
                    ? `${msg.conversation.application.job.title} — ${msg.conversation.application.candidate.name}`
                    : "Direct Message"),
            content: msg.content,
            sender: msg.sender,
            createdAt: msg.created_at,
        }));

        return NextResponse.json({ results: formattedResults, count: formattedResults.length });
    } catch (error) {
        console.error("Message Search Error:", error);
        return NextResponse.json({ error: "Failed to search messages" }, { status: 500 });
    }
}
