<?php

namespace Tests;

use Database\Seeders\Global\GlobalRoleSeed;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Mtc\MercuryDataModels\Tenant;
use Mtc\MercuryDataModels\User;

trait UserForTenant
{
    protected User $user;

    protected function getUser($role = 'mtc'): User
    {
        if ($this instanceof TenantTestCase) {
            $this->user = \Mockery::mock(User::class)->makePartial();
            $this->user->id = 123;
            $this->user->shouldReceive('hasRole')
                ->andReturn(true);
            $this->user->shouldReceive('hasPermissionTo')
                ->andReturn(true);
            $this->user->shouldReceive('latestUnreadReleaseNote')
                ->andReturn(null);
            Auth::setUser($this->user);
            return $this->user;
        }
        if (empty($this->user)) {
            $this->user = User::factory()->create();
            if ($role) {
                (new (GlobalRoleSeed::class))->run();
                if (!empty(tenant('id'))) {
                    $this->user->tenants()->attach(tenant('id'), ['role' => $role]);
                }

                if ($role === 'mtc') {
                    $this->user->assignRole($role);
                }
            }
        }
        return $this->user;
    }
}
