<?php

namespace App\Mcp\Tools\GoogleAds;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Http\Request as HttpRequest;
use Laravel\Ai\Models\Conversation;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;

#[Description('Save one Google campaign field after the user confirms it so the Google chat campaign panel stays current. Call this after every individual field confirmation, before asking for the next field.')]
class UpdateCampaignDraft extends Tool
{
    public function __construct(private readonly HttpRequest $httpRequest) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'field' => $schema->string()->description('Draft field name, such as campaign_name, conversion_goal, daily_budget, or final_url')->required(),
            'value' => $schema->string()->description('The confirmed value for this field')->required(),
        ];
    }

    public function handle(Request $request): Response
    {
        $user = $request->user();
        $data = $request->validate([
            'field' => ['required', 'string', 'max:80', 'regex:/^[a-z][a-z0-9_]*$/'],
            'value' => ['required', 'string', 'max:4000'],
        ]);
        $conversationId = $this->httpRequest->input('conversation');
        $conversation = is_string($conversationId)
            ? Conversation::query()
                ->whereKey($conversationId)
                ->where('chat_type', 'google_ads')
                ->where('participant_type', $user?->getMorphClass())
                ->where('participant_id', $user?->getKey())
                ->first()
            : null;

        if ($user === null || $conversation === null) {
            return Response::error('Google chat conversation not found. Confirm the field in the active Google chat.');
        }

        $draft = json_decode((string) $conversation->google_campaign_draft, true);
        $draft = is_array($draft) ? $draft : [];
        $field = match (strtolower($data['field'])) {
            'location', 'target_location', 'target_locations' => 'locations',
            'language', 'target_language', 'target_languages' => 'languages',
            default => $data['field'],
        };
        $draft[$field] = $data['value'];
        $conversation->update(['google_campaign_draft' => json_encode($draft)]);

        return Response::json(['ok' => true, 'field' => $field, 'value' => $data['value']]);
    }
}
