<?php

namespace Modules\Routing\Filament\Resources\EvRoutes;

use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Modules\Routing\Filament\Resources\EvRoutes\Pages\CreateEvRoute;
use Modules\Routing\Filament\Resources\EvRoutes\Pages\EditEvRoute;
use Modules\Routing\Filament\Resources\EvRoutes\Pages\ListEvRoutes;
use Modules\Routing\Filament\Resources\EvRoutes\Schemas\EvRouteForm;
use Modules\Routing\Filament\Resources\EvRoutes\Tables\EvRoutesTable;
use Modules\Routing\Models\EvRoute;
use UnitEnum;

class EvRouteResource extends Resource
{
    protected static ?string $model = EvRoute::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedMap;

    protected static string|UnitEnum|null $navigationGroup = 'Routing';

    public static function form(Schema $schema): Schema
    {
        return EvRouteForm::configure($schema);
    }

    public static function table(Table $table): Table
    {
        return EvRoutesTable::configure($table);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListEvRoutes::route('/'),
            'create' => CreateEvRoute::route('/create'),
            'edit' => EditEvRoute::route('/{record}/edit'),
        ];
    }

    /**
     * A route can only be activated once every non-blocked vehicle option
     * carries a price above 0 — enforced here (form/UI level), not as a DB
     * constraint. A route with every option blocked can never be activated.
     *
     * Checked against the raw pricing repeater data submitted on the form
     * (not a DB read), since on the create form no pricing rows exist yet,
     * and on the edit form the repeater's relationship save hasn't run yet
     * by the time this is checked.
     *
     * @param  array<int, array{price?: mixed, is_blocked?: mixed}>  $pricingItems
     */
    public static function hasCompletePricingData(array $pricingItems): bool
    {
        $nonBlocked = collect($pricingItems)->reject(fn (array $item) => (bool) ($item['is_blocked'] ?? false));

        return $nonBlocked->isNotEmpty() && $nonBlocked->every(fn (array $item) => (float) ($item['price'] ?? 0) > 0);
    }
}
