<?php

namespace Modules\User\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Modules\User\Models\User;
use Modules\User\Models\Role;

use Modules\Main\Models\Company\CompanyAdmin;
use Modules\Main\Models\Agent\Agent;
use Modules\CityManager\Models\CityManager;

class UserRole extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'role_id',
    ];

    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }
    public static function create(array $attributes = [])
    {
        return parent::updateOrCreate($attributes);
    }

    protected static function booted()
    {
        static::deleted(function (UserRole $userRole)
        {
            $userId = $userRole->user_id;
            switch ($userRole->role_id) {
                case Role::AGENT :
                    Agent::where('user_id', $userId)->delete();
                    break;
                case Role::COMPANY_ADMIN :
                    CompanyAdmin::where('user_id', $userId)->delete();
                    break;
                case Role::CITY_MANAGER :
                    CityManager::where('user_id', $userId)->delete();
                    break;
            }
        });
    }
}
