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


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 });
  }
}

export async function POST(request: NextRequest) {
  try {
    await dbConnect();
    const body  = await request.json();
    const store = await Store.create(body);
    return NextResponse.json({ success: true, data: store }, { status: 201 });
  } catch (error: any) {
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}

export async function PUT(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();
    const body  = await request.json();
    const url = new URL(request.url);
    const id = url.pathname.split('/').pop();
    const store = await Store.findByIdAndUpdate(
      id,
      { $set: body },
      { new: true, runValidators: true }
    );
    if (!store) return NextResponse.json({ success: false, error: "Store not found" }, { status: 404 });
    return NextResponse.json({ success: true, data: store });
  } catch (error: any) {
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();
    const params = context ? await context.params : undefined;
    const store = await Store.findByIdAndDelete(params?.id ?? new URL(request.url).pathname.split('/').pop());
    if (!store) return NextResponse.json({ success: false, error: "Store not found" }, { status: 404 });
    return NextResponse.json({ success: true, message: "Store deleted successfully" });
  } catch (error: any) {
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}