<?php

namespace App\Http\Controllers\API\DeliveryBoy;

use App\Http\Controllers\Controller;
use App\Models\DeliveryBoy;
use App\Models\Delivery;
use App\Services\LocationTrackingService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class LocationController extends Controller
{
    protected $locationService;

    public function __construct(LocationTrackingService $locationService)
    {
        $this->locationService = $locationService;
    }

    public function update(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'latitude' => 'required|numeric|between:-90,90',
            'longitude' => 'required|numeric|between:-180,180',
            'accuracy' => 'nullable|numeric|min:0',
            'speed' => 'nullable|numeric|min:0',
            'heading' => 'nullable|numeric|between:0,360',
        ]);

        $deliveryBoy = $request->user()->deliveryBoy;

        $location = $this->locationService->updateLocation(
            $deliveryBoy,
            $validated['latitude'],
            $validated['longitude'],
            [
                'accuracy' => $validated['accuracy'] ?? null,
                'speed' => $validated['speed'] ?? null,
                'heading' => $validated['heading'] ?? null,
            ]
        );

        return response()->json([
            'success' => true,
            'data' => $location
        ]);
    }

    public function trackDelivery(Request $request, Delivery $delivery): JsonResponse
    {
        $user = $request->user();
        $userRoles = $user->roles->pluck('name')->toArray();
        $canTrack = in_array('super-admin', $userRoles) || in_array('admin', $userRoles) || 
                    $delivery->order->user_id === $user->id;

        if (!$canTrack) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 403);
        }

        $route = $this->locationService->getDeliveryRoute($delivery);

        return response()->json(['success' => true, 'data' => $route]);
    }

    public function nearby(Request $request): JsonResponse
    {
        $this->authorize('viewAny', DeliveryBoy::class);

        $validated = $request->validate([
            'latitude' => 'required|numeric|between:-90,90',
            'longitude' => 'required|numeric|between:-180,180',
            'radius' => 'nullable|numeric|min:1|max:50',
        ]);

        $deliveryBoys = $this->locationService->getNearbyDeliveryBoys(
            $validated['latitude'],
            $validated['longitude'],
            $validated['radius'] ?? 5
        );

        return response()->json(['success' => true, 'data' => $deliveryBoys]);
    }
}
