<?php

namespace App\Http\Resources\Api\V1;

use App\Domain\Agent\Models\Agent;
use Illuminate\Http\Request;

/** @mixin Agent */
class AgentResource extends FleetQResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'role' => $this->role,
            'goal' => $this->goal,
            'backstory' => $this->backstory,
            'provider' => $this->provider,
            'model' => $this->model,
            'status' => $this->status->value,
            'config' => $this->config,
            'capabilities' => $this->capabilities,
            'constraints' => $this->constraints,
            'tool_profile' => $this->tool_profile,
            'environment' => $this->environment?->value,
            'budget_cap_credits' => $this->budget_cap_credits,
            'budget_spent_credits' => $this->budget_spent_credits,
            'last_health_check' => $this->last_health_check?->toISOString(),
            'skills' => $this->whenLoaded('skills', fn () => $this->skills->map(fn ($skill) => [
                'id' => $skill->id,
                'name' => $skill->name,
                'type' => $skill->type->value,
                /** @phpstan-ignore-next-line property.notFound — `pivot` is dynamically attached by BelongsToMany at runtime */
                'priority' => $skill->pivot?->getAttribute('priority'),
            ])->all()),
            'runtime_state' => $this->whenLoaded('runtimeState', fn () => $this->runtimeState ? [
                'total_executions' => $this->runtimeState->total_executions,
                'total_input_tokens' => $this->runtimeState->total_input_tokens,
                'total_output_tokens' => $this->runtimeState->total_output_tokens,
                'total_cost_credits' => $this->runtimeState->total_cost_credits,
                'last_active_at' => $this->runtimeState->last_active_at?->toISOString(),
            ] : null),
            'created_at' => $this->created_at->toISOString(),
            'updated_at' => $this->updated_at->toISOString(),
        ];
    }
}
