<?php

namespace App\Mcp\Tools\Credential;

use App\Domain\Agent\Models\Agent;
use App\Domain\Credential\Actions\CreateCredentialAction;
use App\Domain\Credential\Enums\CredentialSource;
use App\Domain\Credential\Enums\CredentialType;
use App\Mcp\Attributes\AssistantTool;
use App\Mcp\Concerns\HasStructuredErrors;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;

#[IsDestructive]
#[AssistantTool('write')]
class CredentialCreateTool extends Tool
{
    use HasStructuredErrors;

    protected string $name = 'credential_create';

    protected string $description = 'Creates a credential. Pass agent_id when an agent is the creator — the credential will start as pending_review and require human approval before use. WARNING: secret_data is stored encrypted but flows through the current session.';

    public function schema(JsonSchema $schema): array
    {
        return [
            'name' => $schema->string()
                ->description('Credential name')
                ->required(),
            'type' => $schema->string()
                ->description('Credential type: api_token, oauth2, basic_auth, ssh_key, custom_kv')
                ->enum(['api_token', 'oauth2', 'basic_auth', 'ssh_key', 'custom_kv'])
                ->required(),
            'secret_data' => $schema->object()
                ->description('Secret data object (e.g. {"token": "..."} or {"username": "...", "password": "..."})')
                ->required(),
            'description' => $schema->string()
                ->description('Credential description'),
            'expires_at' => $schema->string()
                ->description('Expiration date in ISO 8601 format (e.g. 2025-12-31T23:59:59Z)'),
            'agent_id' => $schema->string()
                ->description('UUID of the agent creating this credential. Sets creator_source=agent and status=pending_review until a human approves it.'),
        ];
    }

    public function handle(Request $request): Response
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|string|in:api_token,oauth2,basic_auth,ssh_key,custom_kv',
            'secret_data' => 'required|array',
            'description' => 'nullable|string',
            'expires_at' => 'nullable|string|date',
            'agent_id' => 'nullable|uuid',
        ]);
        $teamId = (app()->bound('mcp.team_id') ? app('mcp.team_id') : null) ?? auth()->user()?->current_team_id;
        if (! $teamId) {
            return $this->permissionDeniedError('No current team.');
        }

        try {
            $creatorSource = CredentialSource::Human;
            $creatorType = null;
            $creatorId = null;

            if (! empty($validated['agent_id'])) {
                $agent = Agent::withoutGlobalScopes()
                    ->where('team_id', $teamId)
                    ->find($validated['agent_id']);

                if (! $agent) {
                    return $this->notFoundError('agent');
                }

                $creatorSource = CredentialSource::Agent;
                $creatorType = 'agent';
                $creatorId = $agent->id;
            }

            $credential = app(CreateCredentialAction::class)->execute(
                teamId: $teamId,
                name: $validated['name'],
                credentialType: CredentialType::from($validated['type']),
                secretData: $validated['secret_data'],
                description: $validated['description'] ?? null,
                expiresAt: $validated['expires_at'] ?? null,
                creatorSource: $creatorSource,
                creatorType: $creatorType,
                creatorId: $creatorId,
            );

            return Response::text(json_encode([
                'success' => true,
                'credential_id' => $credential->id,
                'name' => $credential->name,
                'type' => $credential->credential_type->value,
                'status' => $credential->status->value,
                'creator_source' => $credential->creator_source->value,
                'note' => $creatorSource === CredentialSource::Agent
                    ? 'Credential is pending_review. A human must approve it before it can be used.'
                    : null,
            ]));
        } catch (\Throwable $e) {
            throw $e;
        }
    }
}
