<?php

namespace App\Models;

use App\Models\Tenants\Tenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Spatie\Permission\Models\Permission;

class Role extends Model
{
    protected $fillable = [
        'tenant_id',
        'name',
        'description',
        'guard_name',
    ];

    protected $casts = [
        'tenant_id' => 'integer',
    ];

    /**
     * 관계: 테넌트
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class, 'tenant_id');
    }

    /**
     * 관계: 권한 (다대다)
     */
    public function permissions(): BelongsToMany
    {
        return $this->belongsToMany(
            Permission::class,
            'role_has_permissions',
            'role_id',
            'permission_id'
        );
    }

    /**
     * 관계: 사용자 (다대다)
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(
            User::class,
            'model_has_roles',
            'role_id',
            'model_id'
        )->wherePivot('model_type', User::class);
    }
}
