<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Workspace extends Model
{
    /** @use HasFactory<\Database\Factories\WorkspaceFactory> */
    use HasFactory;

    protected $guarded = [];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'archived_at' => 'datetime',
            'closed_at' => 'datetime',
        ];
    }

    /**
     * @return BelongsTo<PlatformUser, $this>
     */
    public function closedByPlatformUser(): BelongsTo
    {
        return $this->belongsTo(PlatformUser::class, 'closed_by_platform_user_id');
    }

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

    /**
     * @return BelongsToMany<User, $this>
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'workspace_memberships')
            ->using(WorkspaceMembership::class)
            ->withPivot(['id', 'role'])
            ->withTimestamps();
    }

    /**
     * @return HasMany<ManagedEnvironment, $this>
     */
    public function tenants(): HasMany
    {
        return $this->managedEnvironments();
    }

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

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

    /**
     * @return HasOne<WorkspaceSubscription, $this>
     */
    public function subscription(): HasOne
    {
        return $this->hasOne(WorkspaceSubscription::class);
    }

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

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

    public function isClosed(): bool
    {
        return $this->closed_at !== null;
    }

    public function isArchived(): bool
    {
        return $this->archived_at !== null;
    }

    public function isSelectableAsContext(): bool
    {
        return ! $this->isArchived() && ! $this->isClosed();
    }

    public function closureReason(): ?string
    {
        $reason = trim((string) $this->closed_reason);

        return $reason === '' ? null : $reason;
    }
}
