<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use App\Support\TenantPermissionCatalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class RoleProfile extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'tenant_id',
        'name',
        'description',
        'base_role',
        'permissions',
        'is_system',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'permissions' => 'array',
            'is_system' => 'boolean',
            'is_active' => 'boolean',
        ];
    }

    public function users(): HasMany
    {
        return $this->hasMany(User::class);
    }

    public function hasPermission(string $permission): bool
    {
        return $this->is_active && in_array($permission, $this->permissions ?? [], true);
    }

    public function permissionCount(): int
    {
        return count($this->permissions ?? []);
    }

    public static function createDefaultsForTenant(Tenant $tenant): void
    {
        foreach (TenantPermissionCatalog::defaultProfiles() as $baseRole => $profile) {
            self::withoutGlobalScopes()->firstOrCreate(
                [
                    'tenant_id' => $tenant->id,
                    'base_role' => $baseRole,
                    'is_system' => true,
                ],
                [
                    'name' => $profile['name'],
                    'description' => $profile['description'],
                    'permissions' => TenantPermissionCatalog::defaultForRole($baseRole),
                    'is_active' => true,
                ],
            );
        }
    }
}
