<?php

/** @noinspection LaravelUnknownEloquentFactoryInspection */

namespace DefStudio\GameEngine\Models;

use DefStudio\GameEngine\Enums\Role;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use DefStudio\GameEngine\Models\Concerns\DefinesAwards;
use DefStudio\GameEngine\Models\Contracts\AwardsDefiner;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use DefStudio\GameEngine\Models\Concerns\CanCheckRelationships;
use DefStudio\GameEngine\Database\Factories\OrganizationFactory;

/**
 * @property string $name
 * @property-read object $pivot
 *
 * @method static OrganizationFactory factory(array|callable|int|null $count = null, array|callable $state = [])
 */
class Organization extends Model implements AwardsDefiner
{
    use HasFactory;
    use DefinesAwards;
    use CanCheckRelationships;

    protected $fillable = [
        'name',
    ];

    public function getTable()
    {
        return config('game-engine.organizations.table', parent::getTable());
    }

    protected static function newFactory(): OrganizationFactory
    {
        return OrganizationFactory::new();
    }

    /**
     * @return BelongsToMany<User>
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(\game_engine()->userClass())
            ->withPivot('role');
    }

    /**
     * @return BelongsToMany<User>
     */
    public function players(): BelongsToMany
    {
        return $this->belongsToMany(\game_engine()->userClass(), 'organization_user')
            ->wherePivot('role', Role::player->value)
            ->withPivot('role');
    }

    /**
     * @return BelongsToMany<User>
     */
    public function masters(): BelongsToMany
    {
        return $this->belongsToMany(\game_engine()->userClass(), 'organization_user')
            ->wherePivot('role', Role::master->value)
            ->withPivot('role');
    }

    /**
     * @return BelongsToMany<User>
     */
    public function admins(): BelongsToMany
    {
        return $this->belongsToMany(\game_engine()->userClass(), 'organization_user')
            ->wherePivot('role', Role::admin->value)
            ->withPivot('role');
    }

    /**
     * @return HasMany<Story>
     */
    public function stories(): HasMany
    {
        return $this->hasMany(Story::class);
    }

    /**
     * @return HasMany<Team>
     */
    public function teams(): HasMany
    {
        return $this->hasMany(\game_engine()->teamClass());
    }

    public function award_scope_label(): string
    {
        return __('Organization: :organization_name', ['organization_name' => $this->name]);
    }
}
