<?php

namespace App\Filament\Widgets;

use App\Models\Inventory\StockBatch;
use App\Models\Scopes\BranchScope;
use App\Services\CurrentContext;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\Auth;

class PriceVsStockScatterChart extends ChartWidget
{
    protected static ?int $sort = 18;

    protected ?string $heading = 'Price vs. stock';

    protected ?string $description = 'Each point is a receipt lot: sale price vs. units left on that lot.';

    protected int|string|array $columnSpan = 1;

    public static function canView(): bool
    {
        return Auth::user()?->hasPermissionTo('dashboard.access') ?? false;
    }

    protected function getData(): array
    {
        $branchId = app(CurrentContext::class)->branchId();

        // One point per sellable lot — a product received at two prices shows
        // as two points instead of one product-wide average. Branch semantics
        // mirror Product::withStockFor(): an explicit branch pins the query to
        // it, null aggregates the accessible branches.
        $points = StockBatch::query()
            ->when($branchId !== null, fn ($q) => $q
                ->withoutGlobalScope(BranchScope::class)
                ->where('branch_id', $branchId))
            ->whereHas('product', fn ($q) => $q->where('is_active', true))
            ->active()
            ->where('available_quantity', '>', 0)
            ->whereNotNull('sale_price')
            ->orderByDesc('available_quantity')
            ->limit(60)
            ->get(['id', 'sale_price', 'available_quantity'])
            ->map(fn (StockBatch $lot): array => [
                'x' => round((float) $lot->sale_price, 2),
                'y' => round((float) ($lot->available_quantity ?? 0), 2),
            ])
            ->all();

        return [
            'datasets' => [[
                'label' => 'Lots',
                'data' => $points,
                'backgroundColor' => 'rgba(16, 185, 129, 0.6)',
                'borderColor' => '#10b981',
            ]],
            'labels' => [],
        ];
    }

    protected function getType(): string
    {
        return 'scatter';
    }
}
