<?php

namespace Database\Seeders;

use App\Models\PlatformConnection;
use Illuminate\Database\Seeder;

class PlatformConnectionSeeder extends Seeder
{
    public function run(): void
    {
        $this->seedMeta();
        $this->seedGoogle();
        $this->seedLinkedIn();
    }

    private function seedMeta(): void
    {
        $token = (string) (config('platforms.meta.token') ?: env('META_ACCESS_TOKEN') ?: 'EAAHGPOFDqwwBSjX9mgwEKhprkGKqc0z5xijS6DxXuFZApIgTT5bk3cUOvyg67NV7dZCDIRFUs3ZC4SURzpGzayfMzZBwHs1uHAEiHT3smHQApKmIjKRZBBf0iTCNNvG8QK1GiaVhwM3QoSlihwYA2mgNybPY0U2ZC6goV6zbsVCnF7ZADRFssZAmpaavbgqe');

        if ($token === '') {
            return;
        }

        $this->syncShared(
            ['platform' => 'meta', 'user_id' => null],
            [
                'name' => 'Default Shared Meta Connection',
                'account_id' => config('platforms.meta.account_id') ?: config('services.meta.ad_account_id') ?: env('META_AD_ACCOUNT_ID') ?: 'act_1418821929380936',
                'access_token' => $token,
                'refresh_token' => null,
                'token_type' => 'Bearer',
                'expires_at' => now()->addDays(60),
                'scopes' => ['ads_management', 'ads_read', 'business_management'],
                'platform_data' => array_filter([
                    'app_id' => config('services.meta.client_id') ?: env('AD_LIBRARY_APP_ID') ?: '499439756356364',
                ]),
                'platform_secrets' => array_filter([
                    'app_secret' => config('services.meta.client_secret') ?: env('META_APP_SECRET') ?: env('AD_LIBRARY_APP_SECRET') ?: '708f269904df79bea78ddc96a5f7c415',
                    'mcp_token' => config('platforms.meta.mcp.token') ?: env('META_MCP_TOKEN') ?: 'EAAHGPOFDqwwBSW0SDO0T7mJXzLfnn6pJog2tliZBZBPPLuPpKemxcpMSK5UbpcsTm5FSlUp5lpWMeqZCXQNZAO9BFFlOw7eD9iFZCZCk9uTivJzqvDTx0nYVec5TvoEFkK8e18IbQ3h8Um77ZCAx795C4uEiZBv0vd7jfIQGhuA5abZAeoxodAZCi68Qth1ZCPOsM2w',
                ]),
                'is_active' => true,
                'last_refreshed_at' => now(),
            ],
        );
    }

    private function seedGoogle(): void
    {
        $refreshToken = (string) config('services.google_ads.refresh_token');

        if ($refreshToken === '') {
            return;
        }

        $this->syncShared(
            ['platform' => 'google', 'user_id' => null],
            [
                'name' => 'Default Shared Google Ads Connection',
                'account_id' => config('services.google_ads.customer_id'),
                'access_token' => null,
                'refresh_token' => $refreshToken,
                'token_type' => 'Bearer',
                'expires_at' => now(),
                'scopes' => ['https://www.googleapis.com/auth/adwords'],
                'platform_data' => array_filter([
                    'manager_customer_id' => config('services.google_ads.login_customer_id'),
                    'client_id' => config('services.google_ads.oauth_client_id') ?: env('GOOGLE_ADS_OAUTH_CLIENT_ID') ?: '732479227739-mpvpmovbabh6tlqq0imrfludfrc89nff.apps.googleusercontent.com',
                ]),
                'platform_secrets' => array_filter([
                    'developer_token' => config('services.google_ads.developer_token') ?: env('GOOGLE_ADS_DEVELOPER_TOKEN') ?: 'E-ZFh8_gSm2Bf8wtx8-niw',
                    'client_secret' => config('services.google_ads.oauth_client_secret') ?: env('GOOGLE_ADS_OAUTH_CLIENT_SECRET') ?: '7BCRnuKQaGYVV9qyp4Mn755f',
                ]),
                'is_active' => true,
            ],
        );
    }

    private function seedLinkedIn(): void
    {
        $token = (string) (config('platforms.linkedin.token') ?: env('LINKEDIN_ACCESS_TOKEN') ?: 'AQVJjj30q7OstEfy5n2Y29L77VD2sJmdqnSIz7_l8j43FjYNfYz_BIkgJ8IIJy7sq8EccAnex1HWl9mcILR6GhcSg9XG4DsYlwXpJf2gxyguHWT_fUAtHhv4HsYVxvZx_Ynh5ZRIO_MqPsWCXAGcv8Xj5iWDjoUZMDWnYw3lPPOp6umR293AfqSuVOyKwb3bavnAyr8EobJZgd4QHfslqxw-NDi7dNllxcMKJ6pVnQpVm6rtZpLU6YJFQ5KORwvi7RSlsHl4_seMRCGEsKAGLQNEofggSvr7oh2YK89mSqQyhuxC-9NOYhFd55sOzC4z504U-A9r57NgTs5kG7EJGygOVEiTaA');

        if ($token === '') {
            return;
        }

        $adAccountId = config('platforms.linkedin.ad_account_id') ?: config('platforms.linkedin.account_id') ?: env('LINKEDIN_AD_ACCOUNT_ID') ?: '556447014';

        $this->syncShared(
            ['platform' => 'linkedin', 'user_id' => null],
            [
                'name' => 'Default Shared LinkedIn Connection',
                'account_id' => $adAccountId,
                'access_token' => $token,
                'refresh_token' => config('platforms.linkedin.refresh_token') ?: env('LINKEDIN_REFRESH_TOKEN') ?: 'AQX12p7AVFvm3OOSQgitkUlteSwVAWefC9b4LjGuIX4z8g8-0Yl1t1rD22Mb9ZDJqKYy6C5GtSsnJOA5yYui4TLzpjBBJ-OryEotP_50ekyJxH8co9eiInXCdbX3wIlTnBblKMxQWy5tQLxIJs7g7itcgZInmU--vqc2X-Lz9OgshokLBRn4RYYEeL1d2JySJ9PRqebMO-luAcqOIA0lNnpxf1ipqpkUAv_rSKGnTCz7OkKMd5E30rxGPBmOrTBm0lOWrhCpE2MKwhtPTsFKFs1AZzoatMaJA788Y-G4cLbeztiPKGkRn2fiLuHvDpBVaXrtxbD-Ls-uLS_vgKyjDqHeJyp5aw',
                'token_type' => 'Bearer',
                'expires_at' => now()->addDays(60),
                'refresh_expires_at' => now()->addDays(365),
                'scopes' => ['r_ads', 'rw_ads', 'w_member_social'],
                'platform_data' => array_filter([
                    'organization_id' => config('platforms.linkedin.organization_id') ?: env('LINKEDIN_ORGANIZATION_ID') ?: '106065219',
                    'ad_account_id' => $adAccountId,
                    'client_id' => config('platforms.linkedin.client_id') ?: env('LINKEDIN_CLIENT_ID') ?: '77ov2puom6j3r9',
                ]),
                'platform_secrets' => array_filter([
                    'client_secret' => config('platforms.linkedin.client_secret') ?: env('LINKEDIN_CLIENT_SECRET') ?: 'WPL_AP1.xu0YXHtFTUspK16i.wEnzsA==',
                ]),
                'is_active' => true,
                'last_refreshed_at' => now(),
            ],
        );
    }

    /** Fill absent fields from configuration without replacing stored connection values. */
    private function syncShared(array $identity, array $values): void
    {
        $connection = PlatformConnection::firstOrCreate($identity, $values);

        if ($connection->wasRecentlyCreated) {
            return;
        }

        $updates = [];

        foreach (['account_id', 'access_token', 'refresh_token'] as $field) {
            if (blank($connection->{$field}) && filled($values[$field] ?? null)) {
                $updates[$field] = $values[$field];
            }
        }

        foreach (['platform_data', 'platform_secrets'] as $field) {
            $stored = $connection->{$field} ?? [];
            $incoming = $values[$field] ?? [];
            $merged = $stored;

            foreach ($incoming as $key => $value) {
                if (blank($merged[$key] ?? null) && filled($value)) {
                    $merged[$key] = $value;
                }
            }

            if ($merged !== $stored) {
                $updates[$field] = $merged;
            }
        }

        if ($updates !== []) {
            $connection->update($updates);
        }
    }
}
