<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Targeting\PublishedLocationReadback;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\Auth;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

class ReviewPublishedLocation implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly PublishedLocationReadback $readback,
    ) {}

    public function description(): Stringable|string
    {
        return 'Read the current Meta or Google location targeting of the focused published campaign '
            .'and compare it with the saved published selection. This only reads provider data; it does not change targeting.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [];
    }

    public function handle(Request $request): Stringable|string
    {
        if (! $campaign = $this->focused()) {
            return $this->noCampaign();
        }

        if (Auth::id() === null || (string) Auth::id() !== (string) $campaign->user_id) {
            return $this->json(['ok' => false, 'error' => 'This campaign does not belong to the signed-in user.']);
        }

        try {
            $result = $this->readback->inspect($campaign);

            return $this->json(['ok' => true, ...$result]);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }
}
