<?php

namespace App\Mcp\Tools\Broadcast;

use App\Domain\Broadcast\Actions\CancelBroadcast;
use App\Domain\Broadcast\Models\Broadcast;
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 BroadcastCancelTool extends Tool
{
    use HasStructuredErrors;

    protected string $name = 'broadcast_cancel';

    protected string $description = 'Cancel a broadcast that has not yet finished sending.';

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

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

        $teamId = app('mcp.team_id') ?? auth()->user()?->current_team_id;
        if (! $teamId) {
            return $this->failedPreconditionError('No team context available.');
        }

        $broadcast = Broadcast::withoutGlobalScopes()
            ->where('team_id', $teamId)
            ->find($validated['broadcast_id']);

        if (! $broadcast) {
            return $this->notFoundError('broadcast', $validated['broadcast_id']);
        }

        try {
            $broadcast = app(CancelBroadcast::class)->execute($broadcast);
        } catch (\Throwable $e) {
            return $this->failedPreconditionError($e->getMessage());
        }

        return Response::text(json_encode([
            'id' => $broadcast->id,
            'status' => $broadcast->status->value,
        ]));
    }
}
