<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Services\DistanceCalculatorService;
use App\Models\Restaurant;
use Illuminate\Http\Request;

class DistanceController extends Controller
{
    protected $distanceCalculator;

    public function __construct(DistanceCalculatorService $distanceCalculator)
    {
        $this->distanceCalculator = $distanceCalculator;
    }

    public function calculate(Request $request)
    {
        $validated = $request->validate([
            'restaurant_id' => 'required|exists:restaurants,id',
            'customer_lat' => 'required|numeric',
            'customer_lng' => 'required|numeric',
        ]);

        $restaurant = Restaurant::findOrFail($validated['restaurant_id']);

        if (!$restaurant->latitude || !$restaurant->longitude) {
            return response()->json(['error' => 'Restaurant location not set'], 400);
        }

        $result = $this->distanceCalculator->calculateDistance(
            $restaurant->latitude,
            $restaurant->longitude,
            $validated['customer_lat'],
            $validated['customer_lng']
        );

        return response()->json([
            'restaurant' => [
                'id' => $restaurant->id,
                'name' => $restaurant->name,
                'latitude' => $restaurant->latitude,
                'longitude' => $restaurant->longitude,
            ],
            'customer' => [
                'latitude' => $validated['customer_lat'],
                'longitude' => $validated['customer_lng'],
            ],
            'distance' => $result
        ]);
    }
}
