import dbConnect from "@/lib/mongodb";
import Store from "@/models/Store";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    const { searchParams } = new URL(request.url);
    const page    = parseInt(searchParams.get("page")  || "1");
    const limit   = parseInt(searchParams.get("limit") || "10");
    const search  = searchParams.get("search");
    const sort    = searchParams.get("sort")  || "createdAt";
    const order   = searchParams.get("order") || "desc";
    // const lat     = searchParams.get("lat");
    // const lng     = searchParams.get("lng");

    await dbConnect();
    const query: any = {};
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: "i" } },
        { brand: { $regex: search, $options: "i" } },
        { address   : { $regex: search, $options: "i" } },
        { phone     : { $regex: search, $options: "i" } },
      ];
    }
    const sortOptions: any = sort === "name"
      ? { name: order === "asc" ? 1 : -1 }
      : { createdAt: order === "asc" ? 1 : -1 };
    const skip   = (page - 1) * limit;
    const stores = await Store.find(query).sort(sortOptions).skip(skip).limit(limit).lean();
    const total  = await Store.countDocuments(query);
    return NextResponse.json({ success: true, data: stores, pagination: { page, limit, total, pages: Math.ceil(total / limit) } });

  } catch (error: any) {
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}