<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Targeting\PublishedLocationApprovalBinding;
use App\Campaigns\Targeting\PublishedLocationEditor;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Approvals\Approval;
use Laravel\Ai\Concerns\InteractsWithApprovals;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

/** Apply exactly one approved, reviewed location edit to an existing campaign. */
class ApplyPublishedLocationChange implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly PublishedLocationApprovalBinding $approvalBinding,
        private readonly PublishedLocationEditor $editor,
    ) {}

    public function description(): Stringable|string
    {
        return 'Apply a previously previewed city or region add/remove/replace to the focused published Meta or Google campaign. '
            .'Provide the exact mapping ID and targeting revision from the preview. This edits the provider only after human approval.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'operation' => $schema->string()->description('add, remove, or replace.')->required(),
            'mapping_id' => $schema->integer()->description('Exact mapping ID from the location preview.')->required(),
            'replace_mapping_id' => $schema->integer()->description('Existing selected mapping ID to replace; required only for replace.'),
            'expected_revision' => $schema->integer()->description('Targeting revision from the location preview.')->required(),
        ];
    }

    protected function needsApproval(Request $request): Approval
    {
        return $this->approvalBinding->request($request, $this->focused());
    }

    public function handle(Request $request): Stringable|string
    {
        if (! config('platforms.guardrails.published_location_edits_enabled', false)) {
            return $this->json(['ok' => false, 'error' => 'Published location edits are disabled until paused-provider validation is complete.']);
        }

        $approved = $this->approvalBinding->consume($request);

        if ($approved === null) {
            return $this->json(['ok' => false, 'error' => 'The location approval expired or changed. Preview and review the edit again.']);
        }

        try {
            $result = $this->editor->apply($approved['campaign'], $approved['plan'], $approved['decision']);

            return $this->json(['ok' => true, 'applied' => true, 'result' => $result]);
        } catch (Throwable $exception) {
            return $this->json([
                'ok' => false, 'applied' => false,
                'error' => $exception->getMessage(),
                'note' => 'Review current provider and local targeting before another edit. A provider write may have succeeded even if confirmation failed.',
            ]);
        }
    }
}
