<?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_create_campaign_group')]
#[Description('Create a LinkedIn Campaign Group in PAUSED state.')]
class LinkedInCreateCampaignGroup extends Tool
{
    public function __construct(
        private readonly LinkedInRestApi $api,
    ) {}

    public function handle(Request $request): Response
    {
        $accountId = (string) $request->get('ad_account_id');
        $name = (string) $request->get('name');
        if (! str_starts_with($name, 'ARB-')) {
            $name = 'ARB-'.$name;
        }
        // Always a draft, whatever was asked for.
        //
        // This defaulted to PAUSED and forced PAUSED when a config switch was off,
        // which meant an MCP caller could create a live campaign group by setting
        // one env var - no approval, no decision row, nothing on screen. And PAUSED
        // is the wrong safe value anyway: LinkedIn refuses a group created that way
        // with "status cannot be changed from null to PAUSED".
        //
        // Everything this product builds is a draft, and starting it is an approved
        // act with a tool of its own. An MCP tool is not where that decision is
        // taken, so it does not take it.
        $status = 'DRAFT';

        $result = $this->api->createCampaignGroup($accountId, [
            'name' => $name,
            'status' => $status,
        ]);

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

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_account_id' => $schema->string()
                ->description('LinkedIn Sponsored Account ID or URN.')
                ->required(),
            'name' => $schema->string()
                ->description('Campaign group display name.')
                ->required(),
            'status' => $schema->string()
                ->description('Initial status (defaults to PAUSED).')
                ->enum(['PAUSED', 'ACTIVE']),
        ];
    }
}
