<?php

namespace App\Mcp\Tools\Skill;

use App\Domain\Skill\Actions\UpdateSkillAction;
use App\Domain\Skill\Models\Skill;
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]
class SkillUpdateTool extends Tool
{
    use HasStructuredErrors;

    protected string $name = 'skill_update';

    protected string $description = 'Update an existing skill. Only provided fields will be changed.';

    public function schema(JsonSchema $schema): array
    {
        return [
            'skill_id' => $schema->string()
                ->description('The skill UUID')
                ->required(),
            'name' => $schema->string()
                ->description('New skill name'),
            'description' => $schema->string()
                ->description('New skill description'),
            'prompt_template' => $schema->string()
                ->description('New system prompt template'),
            'data_classification' => $schema->string()
                ->description('Data classification level: public, internal, confidential, restricted.')
                ->enum(['public', 'internal', 'confidential', 'restricted']),
        ];
    }

    public function handle(Request $request): Response
    {
        $validated = $request->validate([
            'skill_id' => 'required|string',
            'name' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'prompt_template' => 'nullable|string',
            'data_classification' => 'nullable|string|in:public,internal,confidential,restricted',
        ]);

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

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

        $attributes = array_filter([
            'name' => $validated['name'] ?? null,
            'description' => $validated['description'] ?? null,
            'system_prompt' => $validated['prompt_template'] ?? null,
            'data_classification' => $validated['data_classification'] ?? null,
        ], fn ($v) => $v !== null);

        if (empty($attributes)) {
            return $this->invalidArgumentError('No fields to update. Provide at least one of: name, description, prompt_template.');
        }

        try {
            $result = app(UpdateSkillAction::class)->execute(
                skill: $skill,
                attributes: $attributes,
                updatedBy: auth()->id(),
            );

            return Response::text(json_encode([
                'success' => true,
                'skill_id' => $result->id,
                'updated_fields' => array_keys($attributes),
            ]));
        } catch (\Throwable $e) {
            throw $e;
        }
    }
}
