<?php

namespace Database\Seeders;

use App\Models\AllowedAdAccount;
use App\Models\GoogleAdsConnection;
use Illuminate\Database\Seeder;

class AllowedAdAccountSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(?string $raw = null): void
    {
        $raw ??= (string) env('PLATFORM_ALLOWED_AD_ACCOUNTS', '');
        $entries = array_values(array_filter(array_map('trim', explode(',', $raw))));

        if ($entries === []) {
            return;
        }

        $linkedInConfigId = (string) config('platforms.linkedin.ad_account_id', '');
        $googleConfigId = (string) (GoogleAdsConnection::shared()?->customer_id ?? '');

        // Collect any URN bare IDs in the same list to disambiguate bare numeric IDs
        $knownLinkedInIds = array_filter([
            AllowedAdAccount::normalizeAccountId($linkedInConfigId, 'linkedin'),
            ...array_map(
                fn (string $e): ?string => str_starts_with($e, 'urn:li:') ? AllowedAdAccount::normalizeAccountId($e, 'linkedin') : null,
                $entries,
            ),
        ]);

        foreach ($entries as $entry) {
            $parsed = $this->detectPlatformAndId($entry, $knownLinkedInIds, $googleConfigId);

            if ($parsed === null) {
                continue;
            }

            [$platform, $accountId] = $parsed;

            AllowedAdAccount::updateOrCreate(
                [
                    'platform' => $platform,
                    'account_id' => $accountId,
                ],
                [
                    'is_active' => true,
                    'notes' => 'Seeded from PLATFORM_ALLOWED_AD_ACCOUNTS',
                ],
            );
        }
    }

    /**
     * Determine platform and canonical account ID for an allowlist entry.
     *
     * @param  list<string>  $knownLinkedInIds
     * @return array{0: string, 1: string}|null
     */
    private function detectPlatformAndId(string $entry, array $knownLinkedInIds, string $googleConfigId): ?array
    {
        $entry = trim($entry);

        if ($entry === '') {
            return null;
        }

        // 1. Explicit prefix: "platform:account_id" (e.g. google:3460855874, linkedin:556447014, meta:act_123)
        if (str_contains($entry, ':') && ! str_starts_with($entry, 'urn:')) {
            [$platform, $id] = explode(':', $entry, 2);
            $platform = strtolower(trim($platform));
            $accountId = AllowedAdAccount::normalizeAccountId($id, $platform);

            return [$platform, $accountId];
        }

        // 2. Meta: starts with act_
        if (str_starts_with($entry, 'act_')) {
            return ['meta', AllowedAdAccount::normalizeAccountId($entry, 'meta')];
        }

        // 3. LinkedIn URN
        if (str_starts_with($entry, 'urn:li:')) {
            return ['linkedin', AllowedAdAccount::normalizeAccountId($entry, 'linkedin')];
        }

        // 4. Bare numeric IDs
        $bare = AllowedAdAccount::normalizeAccountId($entry, 'google');

        if (in_array($bare, $knownLinkedInIds, true)) {
            return ['linkedin', $bare];
        }

        if ($googleConfigId !== '' && $bare === AllowedAdAccount::normalizeAccountId($googleConfigId, 'google')) {
            return ['google', $bare];
        }

        // Standard Google Ads customer IDs are 10 digits
        if (strlen($bare) === 10) {
            return ['google', $bare];
        }

        // Default heuristic: assume linkedin if 9 digits or under, google if 10
        $platform = strlen($bare) <= 9 ? 'linkedin' : 'google';

        return [$platform, AllowedAdAccount::normalizeAccountId($entry, $platform)];
    }
}
