<?php

declare(strict_types=1);

namespace App\Business\Inventory;

use App\Business\Inventory\Enums\InventorySerialNumberStatus;
use App\Models\DberpInventorySerialNumber;
use Illuminate\Validation\ValidationException;

/**
 * 序列号档案治理：仅允许启停与备注/排序等安全字段维护，禁止绕过库存主链手工改库存态。
 */
final class InventorySerialNumberGovernanceService
{
    /**
     * @return list<string>
     */
    public function allowedGovernanceAttributeNames(): array
    {
        return [
            'remark',
            'sort_order',
        ];
    }

    public function canToggleEnabledState(DberpInventorySerialNumber $serialNumber): bool
    {
        return in_array((string) $serialNumber->status, [
            InventorySerialNumberStatus::InStock->value,
            InventorySerialNumberStatus::Disabled->value,
        ], true);
    }

    public function toggleEnabled(DberpInventorySerialNumber $serialNumber): DberpInventorySerialNumber
    {
        if (! $this->canToggleEnabledState($serialNumber)) {
            throw ValidationException::withMessages([
                'is_enabled' => (string) __('dberp.errors.inventory_serial_number_governance_toggle_blocked'),
            ]);
        }

        if ($serialNumber->is_enabled) {
            $serialNumber->forceFill([
                'is_enabled' => false,
                'status' => InventorySerialNumberStatus::Disabled->value,
            ])->save();

            return $serialNumber->refresh();
        }

        $attributes = ['is_enabled' => true];

        if ($serialNumber->status === InventorySerialNumberStatus::Disabled->value) {
            $attributes['status'] = InventorySerialNumberStatus::InStock->value;
        }

        $serialNumber->forceFill($attributes)->save();

        return $serialNumber->refresh();
    }
}
