<?php

namespace App\Http\Controllers\Api\Owner;

use App\Http\Controllers\Controller;
use App\Models\Listing;
use App\Services\SeaConditions\SeaConditionsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CaptainRecommendationController extends Controller
{
    public function __construct(
        private SeaConditionsService $seaService,
    ) {}

    /**
     * GET /api/owner/recommendations?lat=&lng=&days=14&mode=fish|tour
     * veya
     * GET /api/owner/recommendations?listing_id=&days=14&mode=fish|tour
     */
    public function index(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'lat'        => ['nullable', 'numeric', 'between:-90,90'],
            'lng'        => ['nullable', 'numeric', 'between:-180,180'],
            'listing_id' => ['nullable', 'integer', 'exists:listings,id'],
            'days'       => ['nullable', 'integer', 'min:1', 'max:16'],
            'mode'       => ['nullable', 'string', 'in:fish,tour'],
        ]);

        $lat = $validated['lat'] ?? null;
        $lng = $validated['lng'] ?? null;

        if (!$lat || !$lng) {
            if (!empty($validated['listing_id'])) {
                $listing = Listing::with('city.province')->findOrFail($validated['listing_id']);
                $lat = $listing->latitude ?? $listing->city?->latitude ?? $listing->city?->province?->latitude;
                $lng = $listing->longitude ?? $listing->city?->longitude ?? $listing->city?->province?->longitude;
            }
        }

        // Son çare: kaptanın herhangi bir ilanının konumu
        if (!$lat || !$lng) {
            $user = $request->user();
            $anyListing = Listing::with('city.province')
                ->where('user_id', $user->id)
                ->whereNotNull('latitude')
                ->first();

            if ($anyListing) {
                $lat = $anyListing->latitude;
                $lng = $anyListing->longitude;
            } else {
                $anyListing = Listing::with('city.province')
                    ->where('user_id', $user->id)
                    ->whereHas('city')
                    ->first();

                if ($anyListing) {
                    $lat = $anyListing->city?->latitude ?? $anyListing->city?->province?->latitude;
                    $lng = $anyListing->city?->longitude ?? $anyListing->city?->province?->longitude;
                }
            }
        }

        if (!$lat || !$lng) {
            return response()->json(['error' => 'Konum bilgisi gerekli (lat/lng veya listing_id)'], 422);
        }

        $days = $validated['days'] ?? 14;
        $mode = $validated['mode'] ?? 'fish';

        $result = $this->seaService->getMultiDaySummary($lat, $lng, $days, $mode);

        return response()->json($result);
    }
}
