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

// function getDistance(lat1: number, lng1: number, lat2: number, lng2: number) {
//   const R = 6371;
//   const dLat = ((lat2 - lat1) * Math.PI) / 180;
//   const dLng = ((lng2 - lng1) * Math.PI) / 180;
//   const a =
//     Math.sin(dLat / 2) ** 2 +
//     Math.cos((lat1 * Math.PI) / 180) *
//     Math.cos((lat2 * Math.PI) / 180) *
//     Math.sin(dLng / 2) ** 2;
//   return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// }

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 = { isActive: true };
    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 });
  }
}