<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;

class DberpNumberSequence extends Model
{
    protected $table = 'dberp_number_sequences';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'name',
        'applies_to',
        'prefix',
        'date_segment',
        'serial_digits',
        'pattern',
        'next_value',
        'is_enabled',
        'remark',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'next_value' => 'integer',
            'serial_digits' => 'integer',
            'sort_order' => 'integer',
            'is_enabled' => 'boolean',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (): void {
            throw ValidationException::withMessages([
                'code' => [__('dberp.number_sequence_control.create_forbidden')],
            ]);
        });

        static::updating(function (DberpNumberSequence $sequence): void {
            if ($sequence->isDirty('code')) {
                throw ValidationException::withMessages([
                    'code' => [__('dberp.number_sequence_control.code_immutable')],
                ]);
            }
        });

        static::deleting(function (): void {
            throw ValidationException::withMessages([
                'id' => [__('dberp.number_sequence_control.system_delete_forbidden')],
            ]);
        });
    }
}
