<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpCustomerPriceRules\Pages;

use App\Business\Sales\CustomerPriceRuleService;
use App\Business\Sales\Enums\CustomerPriceRuleStatus;
use App\Filament\Resources\DberpCustomerPriceRules\DberpCustomerPriceRuleResource;
use App\Models\DberpCustomerPriceRule;
use App\Services\DberpPermissionService;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use App\Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class EditDberpCustomerPriceRule extends EditRecord
{
    protected static string $resource = DberpCustomerPriceRuleResource::class;

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        /** @var DberpCustomerPriceRule $record */
        return app(CustomerPriceRuleService::class)->updateRule($record, $data);
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('disable')
                ->label(__('dberp.actions.disable_price_rule'))
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.customer_price_rule_disable'))
                ->visible(fn (DberpCustomerPriceRule $record): bool => $record->status === CustomerPriceRuleStatus::Active->value && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::DISABLE_CUSTOMER_PRICE_RULE))
                ->action(function (): void {
                    app(CustomerPriceRuleService::class)->disableRule($this->record);
                    $this->record->refresh();
                }),
            DeleteAction::make()
                ->visible(fn (DberpCustomerPriceRule $record): bool => $record->status === CustomerPriceRuleStatus::Inactive->value && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::EDIT_CUSTOMER_PRICE_RULE)),
        ];
    }
}