<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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)),
        ];
    }
}