<?php

namespace App\Campaigns;

use App\Models\Campaign;
use App\Services\LinkedIn\LinkedInUrn;
use Illuminate\Support\Str;

/**
 * The ids a publish created, named the way the platform's own interface names them.
 *
 * The panel printed the raw API keys. LinkedIn's API calls the top level a
 * "campaign group" and the level below a "campaign", but Campaign Manager shows
 * them as Campaigns and Ad sets, so "campaign id" pointed at what the buyer sees
 * as an ad set and the ids were reported as swapped. The API name stays as the
 * hint for anyone matching ids against API logs. The ads row was a JSON dump of
 * URNs.
 */
class CreatedIds
{
    /** @var array<string, array<string, array{label: string, hint?: string, pick?: string}>> */
    private const LEVELS = [
        'linkedin' => [
            'campaign_group_id' => ['label' => 'Campaign', 'hint' => 'API: campaign group'],
            'campaign_id' => ['label' => 'Ad set', 'hint' => 'API: campaign'],
            'ads' => ['label' => 'Ads', 'hint' => 'API: creative', 'pick' => 'creative_id'],
        ],
        'meta' => [
            'campaign_id' => ['label' => 'Campaign'],
            'adset_id' => ['label' => 'Ad set'],
            'ad_sets' => ['label' => 'Ad sets', 'pick' => 'adset_id'],
            'ads' => ['label' => 'Ads', 'pick' => 'ad_id'],
        ],
    ];

    /**
     * Top level first, then any key this does not know, humanised.
     *
     * @return list<array{label: string, hint: ?string, ids: list<string>}>
     */
    public static function rows(Campaign $campaign): array
    {
        $stored = (array) ($campaign->external_ids ?? []);
        $levels = self::LEVELS[$campaign->platform] ?? [];

        // A Meta campaign with several ad sets stores both; the list is the full answer.
        if (isset($stored['ad_sets'], $stored['adset_id'])) {
            unset($stored['adset_id']);
        }

        $ordered = [...array_intersect_key($levels, $stored), ...array_diff_key($stored, $levels)];
        $rows = [];

        foreach (array_keys($ordered) as $key) {
            $level = $levels[$key] ?? ['label' => Str::ucfirst(str_replace('_', ' ', Str::beforeLast($key, '_id')))];
            $ids = self::ids($stored[$key], $level['pick'] ?? null);

            if ($ids !== []) {
                $rows[] = ['label' => $level['label'], 'hint' => $level['hint'] ?? null, 'ids' => $ids];
            }
        }

        return $rows;
    }

    /**
     * The two ids the right-hand panel shows for a LinkedIn campaign.
     *
     * Campaign is the campaign group. Ad set is the LinkedIn campaign an edit
     * is sent to. The stored campaign id wins over external_campaign_id when
     * both are present, because that is the id printed on the panel.
     *
     * @return array{campaign_id: ?string, ad_set_id: ?string}
     */
    public static function linkedinPanel(Campaign $campaign): array
    {
        $stored = (array) ($campaign->external_ids ?? []);

        return [
            'campaign_id' => LinkedInUrn::numericId((string) ($stored['campaign_group_id'] ?? '')),
            'ad_set_id' => LinkedInUrn::numericId((string) ($stored['campaign_id'] ?? ''))
                ?? LinkedInUrn::numericId((string) $campaign->external_campaign_id),
        ];
    }

    /** @return list<string> */
    private static function ids(mixed $value, ?string $pick): array
    {
        $values = is_array($value) ? $value : [$value];
        $ids = [];

        foreach ($values as $item) {
            $id = is_array($item) ? ($item[$pick ?? ''] ?? $item['ad_id'] ?? $item['id'] ?? null) : $item;

            if (is_scalar($id) && filled($id)) {
                $ids[] = LinkedInUrn::numericId((string) $id) ?? (string) $id;
            }
        }

        return array_values(array_unique($ids));
    }
}
