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

export async function GET(request: Request) {
    try {
        const { searchParams } = new URL(request.url);
        const query = searchParams.get("q")?.trim();

        if (!query || query.length < 2) {
            return NextResponse.json({ titles: [], companies: [], locations: [], recent: [], popular: [] });
        }

        const currentUser = await getCurrentUser().catch(() => null);

        // Run all queries in parallel for speed
        const [titles, companies, locations, recentSearches] = await Promise.all([
            // Top 5 matching job titles (distinct)
            prisma.job.findMany({
                where: {
                    status: "published",
                    title: { contains: query, mode: "insensitive" },
                },
                select: { title: true },
                distinct: ["title"],
                take: 5,
            }),

            // Top 3 matching company names
            prisma.job.findMany({
                where: {
                    status: "published",
                    company: { contains: query, mode: "insensitive" },
                },
                select: { company: true },
                distinct: ["company"],
                take: 3,
            }),

            // Top 3 matching cities
            prisma.job.findMany({
                where: {
                    status: "published",
                    city: { not: null, contains: query, mode: "insensitive" },
                },
                select: { city: true, state: true, country: true },
                distinct: ["city"],
                take: 3,
            }),

            // Recent searches (if authenticated) 
            currentUser
                ? prisma.searchHistory.findMany({
                    where: {
                        user_id: currentUser.id,
                        query: { contains: query, mode: "insensitive" },
                    },
                    select: { query: true },
                    distinct: ["query"],
                    orderBy: { created_at: "desc" },
                    take: 3,
                })
                : Promise.resolve([]),
        ]);

        return NextResponse.json({
            titles: titles.map((t) => t.title),
            companies: companies.map((c) => c.company),
            locations: locations.map((l) =>
                [l.city, l.state, l.country].filter(Boolean).join(", ")
            ),
            recent: recentSearches.map((r) => r.query),
            popular: getPopularSearches(query),
        });
    } catch (error) {
        console.error("Autocomplete Error:", error);
        return NextResponse.json({ titles: [], companies: [], locations: [], recent: [], popular: [] });
    }
}

function getPopularSearches(query: string): string[] {
    const popular = [
        "Remote jobs",
        "Software engineer",
        "Marketing manager",
        "Data analyst",
        "Customer service",
        "Product manager",
        "Full stack developer",
        "Graphic designer",
        "Sales representative",
        "Project manager",
        "Content writer",
        "UI/UX designer",
        "DevOps engineer",
        "Business analyst",
        "Human resources",
    ];

    return popular
        .filter((p) => p.toLowerCase().includes(query.toLowerCase()))
        .slice(0, 3);
}
