<?php

namespace App\Models;

use App\Support\Concerns\DerivesWorkspaceIdFromTenant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class BaselineTenantAssignment extends Model
{
    use DerivesWorkspaceIdFromTenant;
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'override_scope_jsonb' => 'array',
    ];

    public function workspace(): BelongsTo
    {
        return $this->belongsTo(Workspace::class);
    }

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(ManagedEnvironment::class, 'managed_environment_id');
    }

    public function baselineProfile(): BelongsTo
    {
        return $this->belongsTo(BaselineProfile::class);
    }

    public function assignedByUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'assigned_by_user_id');
    }

    public function scopeForBaselineProfile(Builder $query, BaselineProfile|int $profile): Builder
    {
        $profileId = $profile instanceof BaselineProfile
            ? (int) $profile->getKey()
            : (int) $profile;

        return $query->where('baseline_profile_id', $profileId);
    }

    public function scopeInWorkspace(Builder $query, int $workspaceId): Builder
    {
        return $query->where('workspace_id', $workspaceId);
    }

    public static function assignedTenantIdsForProfile(BaselineProfile|int $profile, ?int $workspaceId = null): array
    {
        return static::query()
            ->when($workspaceId !== null, fn (Builder $query): Builder => $query->inWorkspace($workspaceId))
            ->forBaselineProfile($profile)
            ->pluck('managed_environment_id')
            ->map(static fn (mixed $tenantId): int => (int) $tenantId)
            ->filter(static fn (int $tenantId): bool => $tenantId > 0)
            ->values()
            ->all();
    }
}
