<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Brand extends Model
{
    protected $fillable = ['name', 'slug', 'image', 'is_active'];

    public function getRouteKeyName(): string
    {
        return 'slug';
    }
    protected $casts = ['is_active' => 'boolean'];

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    public static function generateSlug(string $name, ?int $excludeId = null): string
    {
        $base = str_replace(' ', '-', trim($name));
        $slug = $base;
        $counter = 1;
        while (
            static::where('slug', $slug)
                ->when($excludeId, fn($q) => $q->where('id', '!=', $excludeId))
                ->exists()
        ) {
            $slug = $base . '-' . $counter++;
        }
        return $slug;
    }
}
