<?php

namespace App\Models;

use App\Support\Concerns\DerivesWorkspaceIdFromTenant;
use App\Support\Artifacts\ArtifactProviderDetail;
use App\Support\Artifacts\ArtifactSourceDescriptor;
use App\Support\Artifacts\ArtifactSourceResolver;
use App\Support\Inventory\InventoryPolicyTypeMeta;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class InventoryItem extends Model
{
    /** @use HasFactory<\Database\Factories\InventoryItemFactory> */
    use DerivesWorkspaceIdFromTenant;

    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'meta_jsonb' => 'array',
        'last_seen_at' => 'datetime',
    ];

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

    public function lastSeenRun(): BelongsTo
    {
        return $this->belongsTo(OperationRun::class, 'last_seen_operation_run_id');
    }

    public function lastSeenOperationRun(): BelongsTo
    {
        return $this->belongsTo(OperationRun::class, 'last_seen_operation_run_id');
    }

    /**
     * @return array{
     *     canonical_type: string,
     *     provider_object_type: string,
     *     provider_display_type: string,
     *     legacy_policy_type: ?string
     * }
     */
    public function inventoryTypeDescriptor(): array
    {
        return InventoryPolicyTypeMeta::typeDescriptorFor(
            is_string($this->policy_type) ? $this->policy_type : null,
            is_array($this->meta_jsonb) ? $this->meta_jsonb : [],
        );
    }

    public function artifactSourceDescriptor(): ArtifactSourceDescriptor
    {
        return app(ArtifactSourceResolver::class)->forInventoryItem($this);
    }

    public function artifactProviderDetail(): ArtifactProviderDetail
    {
        return app(ArtifactSourceResolver::class)->providerDetailForInventoryItem($this);
    }
}
