<?php

namespace App\Mcp\Tools\GoogleAds;

use App\Models\GoogleAdsCampaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Throwable;

#[Description('Update the name, paused/enabled status, or daily budget of a live Google Ads campaign owned by the authenticated user.')]
class UpdateCampaign extends Tool
{
    public function __construct(private readonly GoogleAdsService $googleAds) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'campaign_id' => $schema->integer()->description('Local campaign record ID')->required(),
            'name' => $schema->string()->description('New campaign name')->required(),
            'status' => $schema->string()->description('Campaign status: paused or enabled')->required(),
            'daily_budget' => $schema->number()->description('New daily budget in the account currency'),
        ];
    }

    public function handle(Request $request): Response
    {
        $user = $request->user();
        if ($user === null) {
            return Response::error('Authentication is required.');
        }

        $data = $request->validate([
            'campaign_id' => ['required', 'integer'],
            'name' => ['required', 'string', 'max:255'],
            'status' => ['required', 'in:paused,enabled'],
            'daily_budget' => ['nullable', 'numeric', 'min:0.01'],
        ]);
        $campaign = GoogleAdsCampaign::query()
            ->where('user_id', $user->getAuthIdentifier())
            ->find($data['campaign_id']);
        if ($campaign === null || blank($campaign->google_campaign_id)) {
            return Response::error('Live Google Ads campaign not found for this user.');
        }
        $connection = GoogleAdsConnection::query()->where('user_id', $user->getAuthIdentifier())->find($campaign->google_ads_connection_id);
        if ($connection === null) {
            return Response::error('Google Ads connection not found.');
        }

        try {
            $this->googleAds->updateCampaign($connection, $campaign, $data);
            $campaign->update($data);
        } catch (Throwable $exception) {
            report($exception);

            return Response::error($exception->getMessage());
        }

        return Response::json(['ok' => true, 'campaign' => $campaign->fresh()->toArray()]);
    }
}
