import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth } from "@/lib/auth";

export const dynamic = "force-dynamic";

// ─── GET /api/halal/user-places ─────────────────────────────
// Returns all user-contributed places, optionally within a bounding box
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get("userId"); // optional filter
    const swLat = searchParams.get("swLat");
    const swLng = searchParams.get("swLng");
    const neLat = searchParams.get("neLat");
    const neLng = searchParams.get("neLng");

    const where: Record<string, unknown> = {};

    if (userId) where.userId = userId;

    if (swLat && swLng && neLat && neLng) {
      where.lat = { gte: parseFloat(swLat), lte: parseFloat(neLat) };
      where.lng = { gte: parseFloat(swLng), lte: parseFloat(neLng) };
    }

    const places = await prisma.userPlace.findMany({
      where,
      orderBy: { createdAt: "desc" },
      include: {
        user: { select: { id: true, name: true } },
      },
    });

    return NextResponse.json({ places });
  } catch (error) {
    console.error("GET /api/halal/user-places error:", error);
    return NextResponse.json(
      { places: [], error: "Failed to fetch user places" },
      { status: 200 }
    );
  }
}

// ─── POST /api/halal/user-places ────────────────────────────
export async function POST(request: NextRequest) {
  try {
    const auth = await requireAuth(request);
    if (!auth) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { name, address, lat, lng, type, notes } = body;

    if (!name || !name.trim()) {
      return NextResponse.json({ error: "Name is required" }, { status: 400 });
    }
    if (lat === undefined || lng === undefined || isNaN(lat) || isNaN(lng)) {
      return NextResponse.json({ error: "Valid coordinates are required" }, { status: 400 });
    }
    if (!["mosque", "restaurant", "cafe"].includes(type)) {
      return NextResponse.json({ error: "Type must be mosque, restaurant, or cafe" }, { status: 400 });
    }

    const place = await prisma.userPlace.create({
      data: {
        userId: auth.userId,
        name: name.trim(),
        address: address?.trim() || "",
        lat,
        lng,
        type,
        notes: notes?.trim() || null,
      },
      include: {
        user: { select: { id: true, name: true } },
      },
    });

    return NextResponse.json({ place }, { status: 201 });
  } catch (error) {
    console.error("POST /api/halal/user-places error:", error);
    return NextResponse.json(
      { error: "Failed to create place" },
      { status: 500 }
    );
  }
}

// ─── DELETE /api/halal/user-places?id=xxx ───────────────────
export async function DELETE(request: NextRequest) {
  try {
    const auth = await requireAuth(request);
    if (!auth) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const id = searchParams.get("id");
    if (!id) {
      return NextResponse.json({ error: "Place ID required" }, { status: 400 });
    }

    const place = await prisma.userPlace.findUnique({ where: { id } });
    if (!place) {
      return NextResponse.json({ error: "Place not found" }, { status: 404 });
    }
    if (place.userId !== auth.userId) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    await prisma.userPlace.delete({ where: { id } });
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("DELETE /api/halal/user-places error:", error);
    return NextResponse.json(
      { error: "Failed to delete place" },
      { status: 500 }
    );
  }
}
