<?php

namespace App\Mcp\Tools\LinkedIn;

use App\Services\LinkedIn\LinkedInRestApi;
use App\Services\LinkedIn\LinkedInUrn;
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_create_creative')]
#[Description('Attach an ad creative to a LinkedIn campaign in PAUSED state.')]
class LinkedInCreateCreative extends Tool
{
    public function __construct(
        private readonly LinkedInRestApi $api,
    ) {}

    public function handle(Request $request): Response
    {
        $accountId = (string) $request->get('ad_account_id');
        $campaignId = (string) $request->get('campaign_id');
        $name = (string) $request->get('name');
        $content = $request->get('content');

        $payload = [
            'campaign' => LinkedInUrn::campaign($campaignId),
            'name' => $name,
            // Draft, like everything else this product creates. It said ACTIVE and
            // was quietly corrected by a guard that has been removed, so it would
            // now do what it says: create a live creative from an MCP call with no
            // approval anywhere near it.
            'intendedStatus' => 'DRAFT',
            'type' => (string) ($request->get('type') ?? 'SPONSORED_STATUS_UPDATE'),
            'content' => is_string($content) ? json_decode($content, true) : $content,
        ];

        $result = $this->api->createCreative($accountId, array_filter($payload));

        return Response::text(json_encode([
            'creative_id' => $result['id'] ?? null,
            'intendedStatus' => 'DRAFT',
            ...$result,
        ], JSON_PRETTY_PRINT));
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_account_id' => $schema->string()
                ->description('LinkedIn Sponsored Account ID or URN.')
                ->required(),
            'campaign_id' => $schema->string()
                ->description('LinkedIn Campaign ID or URN to attach creative to.')
                ->required(),
            'name' => $schema->string()
                ->description('Creative name or headline.')
                ->required(),
            'type' => $schema->string()
                ->description('Creative type (e.g. SPONSORED_STATUS_UPDATE, SPONSORED_VIDEO).'),
            'content' => $schema->string()
                ->description('JSON string or object containing headline, text, media URNs.'),
        ];
    }
}
