<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\MarketPrice;
use App\Support\ApiResponse;
use Illuminate\Http\Request;

class PriceChartController extends Controller
{
    public function __invoke(Request $request)
    {
        $query = MarketPrice::query()->latest('recorded_at')->latest('id');

        if ($request->filled('category_id')) {
            $query->where('category_id', $request->integer('category_id'));
        }

        if ($request->filled('breed_id')) {
            $query->where('breed_id', $request->integer('breed_id'));
        }

        if ($request->filled('province_id')) {
            $query->where('province_id', $request->integer('province_id'));
        }

        if ($request->filled('county_id')) {
            $query->where('county_id', $request->integer('county_id'));
        }

        $items = $query->limit(50)->get();

        if ($items->isEmpty()) {
            $items = MarketPrice::query()->latest('recorded_at')->limit(10)->get();
        }

        // Fallback sample points when table is empty (keeps chart usable before seeding).
        if ($items->isEmpty()) {
            $now = now();
            $samples = [
                ['label' => 'گوساله پرواری', 'price' => 2850000, 'change' => 1.2],
                ['label' => 'بره نر', 'price' => 1950000, 'change' => -0.5],
                ['label' => 'شیر خام', 'price' => 280000, 'change' => 0.8],
            ];

            return ApiResponse::success([
                'items' => $samples,
                'updated_at' => $now->toISOString(),
            ]);
        }

        return ApiResponse::success([
            'items' => $items->map(fn (MarketPrice $price) => [
                'label' => $price->label,
                'price' => (int) $price->price,
                'change' => (float) $price->change,
                'category_id' => $price->category_id,
                'breed_id' => $price->breed_id,
                'province_id' => $price->province_id,
                'county_id' => $price->county_id,
            ])->values(),
            'updated_at' => optional($items->first()->recorded_at ?? $items->first()->updated_at)->toISOString(),
        ]);
    }
}
