<?php

namespace App\Mcp\Tools\Tool;

use App\Domain\Tool\Actions\DeleteToolAction;
use App\Domain\Tool\Models\Tool as ToolModel;
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('destructive')]
class ToolDeleteTool extends Tool
{
    use HasStructuredErrors;

    protected string $name = 'tool_delete';

    protected string $description = 'Delete a tool (soft delete). The tool will be detached from all agents and marked as deleted.';

    public function schema(JsonSchema $schema): array
    {
        return [
            'tool_id' => $schema->string()
                ->description('The tool UUID')
                ->required(),
        ];
    }

    public function handle(Request $request): Response
    {
        $validated = $request->validate([
            'tool_id' => 'required|string',
        ]);

        $teamId = (app()->bound('mcp.team_id') ? app('mcp.team_id') : null) ?? auth()->user()?->current_team_id;
        if (! $teamId) {
            return $this->permissionDeniedError('No current team.');
        }
        $tool = ToolModel::withoutGlobalScopes()->where('team_id', $teamId)->find($validated['tool_id']);

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

        try {
            app(DeleteToolAction::class)->execute($tool);

            return Response::text(json_encode([
                'success' => true,
                'tool_id' => $validated['tool_id'],
                'deleted' => true,
            ]));
        } catch (\Throwable $e) {
            throw $e;
        }
    }
}
