<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class TipoImpuesto extends Model
{
    protected $table = 'tipos_impuesto';

    protected $fillable = ['nombre', 'porcentaje', 'activo', 'predeterminado'];

    protected function casts(): array
    {
        return [
            'porcentaje' => 'decimal:2',
            'activo' => 'boolean',
            'predeterminado' => 'boolean',
        ];
    }

    public static function predeterminado(): self
    {
        return static::where('predeterminado', true)->first() ?? static::firstOrFail();
    }

    public function marcarComoPredeterminado(): void
    {
        DB::transaction(function () {
            static::where('id', '!=', $this->id)->update(['predeterminado' => false]);
            $this->update(['predeterminado' => true]);
        });
    }
}
