<?php

namespace App\Models;

use App\Trait\BelongsToSolicitor;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class WorkboardCategory extends Model
{
    use BelongsToSolicitor;

    protected $fillable = [
        'name',
        'slug',
        'description',
    ];

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (WorkboardCategory $category) {
            $category->slug = static::generateUniqueSlug($category->name, $category->solicitor_id);
        });

        static::updating(function (WorkboardCategory $category) {
            if ($category->isDirty('name')) {
                $category->slug = static::generateUniqueSlug($category->name, $category->solicitor_id, $category->id);
            }
        });
    }

    protected static function generateUniqueSlug(string $name, ?int $solicitorId, ?int $exceptId = null): string
    {
        $base = Str::slug($name);
        $slug = $base;
        $count = 2;

        $query = static::withoutGlobalScopes()->where('solicitor_id', $solicitorId)->where('slug', $slug);

        if ($exceptId) {
            $query->where('id', '!=', $exceptId);
        }

        while ($query->clone()->exists()) {
            $slug = $base . '-' . $count++;
            $query = static::withoutGlobalScopes()->where('solicitor_id', $solicitorId)->where('slug', $slug);
            if ($exceptId) {
                $query->where('id', '!=', $exceptId);
            }
        }

        return $slug;
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }

    public function items()
    {
        return $this->hasMany(WorkboardItem::class);
    }

    public function availableItems()
    {
        return $this->hasMany(WorkboardItem::class)
                    ->whereNull('claimed_by_user_id')
                    ->whereNull('completed_at');
    }
}
