<?php

namespace App\Http\Controllers;

use App\Http\Resources\LocationResource;
use App\Models\Location;
use Illuminate\Http\Request;

class LocationController extends Controller
{
    /**
     * List active reference points; optional ?q search by name/address/city.
     * Available to any authenticated user (clientes pick from these).
     */
    public function index(Request $request)
    {
        $query = Location::query()->where('ativo', true);

        if ($q = trim((string) $request->query('q'))) {
            $query->where(function ($sub) use ($q) {
                $sub->where('nome', 'like', "%{$q}%")
                    ->orWhere('endereco', 'like', "%{$q}%")
                    ->orWhere('cidade', 'like', "%{$q}%");
            });
        }

        return LocationResource::collection($query->orderBy('nome')->get());
    }

    public function store(Request $request)
    {
        $this->ensureAdmin($request);

        $data = $request->validate([
            'nome' => ['required', 'string', 'max:255'],
            'endereco' => ['required', 'string', 'max:255'],
            'cidade' => ['nullable', 'string', 'max:120'],
            'latitude' => ['required', 'numeric', 'between:-90,90'],
            'longitude' => ['required', 'numeric', 'between:-180,180'],
        ]);

        $location = Location::create($data);

        return (new LocationResource($location))->response()->setStatusCode(201);
    }

    public function destroy(Request $request, Location $location)
    {
        $this->ensureAdmin($request);

        $location->delete();

        return response()->json(['message' => 'Ponto removido.']);
    }

    private function ensureAdmin(Request $request): void
    {
        if ($request->user()->role !== 'admin') {
            abort(403, 'Apenas administradores podem gerir pontos.');
        }
    }
}
