<?php

namespace App\Mcp\Tools\LinkedIn;

use App\Services\LinkedIn\LinkedInRestApi;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Attributes\Name;
use Laravel\Mcp\Server\Tool;

#[Name('linkedin_update_entity')]
#[Description('Update a live or paused LinkedIn entity (campaign, campaign group, creative).')]
class LinkedInUpdateEntity extends Tool
{
    public function __construct(
        private readonly LinkedInRestApi $api,
    ) {}

    public function handle(Request $request): Response
    {
        $accountId = (string) $request->get('ad_account_id');
        $entityType = (string) $request->get('entity_type');
        $entityId = (string) $request->get('entity_id');
        $fields = $request->get('fields');

        $patchFields = is_string($fields) ? (json_decode($fields, true) ?: []) : (array) $fields;

        $result = $this->api->updateEntity($accountId, $entityType, $entityId, $patchFields);

        return Response::text(json_encode([
            'updated' => true,
            'entity_id' => $entityId,
            'entity_type' => $entityType,
            ...$result,
        ], JSON_PRETTY_PRINT));
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_account_id' => $schema->string()
                ->description('LinkedIn Sponsored Account ID or URN.')
                ->required(),
            'entity_type' => $schema->string()
                ->description('Entity type: campaign, campaign_group, creative.')
                ->enum(['campaign', 'campaign_group', 'creative'])
                ->required(),
            'entity_id' => $schema->string()
                ->description('Entity ID or URN to update.')
                ->required(),
            'fields' => $schema->string()
                ->description('JSON object of field-value pairs to set (e.g. {"status": "ACTIVE"}).')
                ->required(),
        ];
    }
}
