<?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_campaign')]
#[Description('Create a LinkedIn Campaign with targeting, budget, and objective in PAUSED state.')]
class LinkedInCreateCampaign extends Tool
{
    public function __construct(
        private readonly LinkedInRestApi $api,
    ) {}

    public function handle(Request $request): Response
    {
        $accountId = (string) $request->get('ad_account_id');
        $campaignGroupId = (string) $request->get('campaign_group_id');
        $name = (string) $request->get('name');
        if (! str_starts_with($name, 'ARB-')) {
            $name = 'ARB-'.$name;
        }
        $objective = (string) $request->get('objective');
        $costType = (string) ($request->get('cost_type') ?? 'CPM');
        $dailyBudget = $request->get('daily_budget');
        $targeting = $request->get('targeting') ?? [];
        $parsedTargeting = is_string($targeting) ? json_decode($targeting, true) : $targeting;
        if (empty($parsedTargeting)) {
            $parsedTargeting = [
                'include' => [
                    'and' => [
                        [
                            'or' => [
                                'urn:li:adTargetingFacet:locations' => ['urn:li:geo:103644278'],
                            ],
                        ],
                        [
                            'or' => [
                                'urn:li:adTargetingFacet:interfaceLocales' => ['urn:li:locale:en_US'],
                            ],
                        ],
                    ],
                ],
            ];
        }

        $objectiveType = match (strtoupper((string) $objective)) {
            'WEBSITE_VISITS', 'WEBSITE_VISIT' => 'WEBSITE_VISIT',
            'LEAD_GENERATION' => 'LEAD_GENERATION',
            'BRAND_AWARENESS' => 'BRAND_AWARENESS',
            'ENGAGEMENT' => 'ENGAGEMENT',
            'VIDEO_VIEWS', 'VIDEO_VIEW' => 'VIDEO_VIEW',
            'JOB_APPLY', 'JOB_APPLICANTS', 'JOB_APPLICATION' => 'JOB_APPLICANTS',
            'WEBSITE_CONVERSIONS', 'WEBSITE_CONVERSION' => 'WEBSITE_CONVERSIONS',
            default => $objective ?: 'WEBSITE_VISIT',
        };

        $payload = [
            'campaignGroup' => LinkedInUrn::campaignGroup($campaignGroupId),
            'name' => $name,
            'status' => 'PAUSED',
            'objectiveType' => $objectiveType,
            'costType' => $costType,
            'dailyBudget' => $dailyBudget ? [
                'amount' => (string) $dailyBudget,
                'currencyCode' => (string) ($request->get('currency') ?? 'USD'),
            ] : null,
            'targetingCriteria' => $parsedTargeting,
        ];

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

        return Response::text(json_encode([
            'campaign_id' => $result['id'] ?? null,
            'status' => 'PAUSED',
            ...$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_group_id' => $schema->string()
                ->description('LinkedIn Campaign Group ID or URN.')
                ->required(),
            'name' => $schema->string()
                ->description('Campaign display name.')
                ->required(),
            'objective' => $schema->string()
                ->description('LinkedIn Campaign Objective.')
                ->enum(['BRAND_AWARENESS', 'WEBSITE_VISITS', 'ENGAGEMENT', 'VIDEO_VIEWS', 'LEAD_GENERATION', 'WEBSITE_CONVERSIONS', 'JOB_APPLY'])
                ->required(),
            'daily_budget' => $schema->number()
                ->description('Daily budget amount.')
                ->required(),
            'currency' => $schema->string()
                ->description('Currency code (e.g. USD).'),
            'cost_type' => $schema->string()
                ->description('Cost type: CPM, CPC, CPV.')
                ->enum(['CPM', 'CPC', 'CPV']),
            'targeting' => $schema->string()
                ->description('JSON string or object of targeting criteria.'),
        ];
    }
}
