<?php

namespace Database\Seeders;

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

/**
 * Seeds initial platform connection records from environment variables.
 *
 * =============================================================================
 * FUTURE UI & OAUTH ARCHITECTURE PLAN
 * =============================================================================
 *
 * 1. UI CONNECTION FLOW (Phase 2):
 *    - Endpoints:
 *        GET  /connections/{platform}/connect  -> Redirects user to platform OAuth consent dialog.
 *        GET  /connections/{platform}/callback -> Exchanges authorization code for tokens.
 *    - User Tenancy:
 *        When authenticated users connect via UI, `user_id` will be populated with `auth()->id()`.
 *        System-wide automated agents and cron jobs can fall back to `user_id = null` (shared).
 *
 * 2. WHAT BELONGS IN DATABASE vs CONFIG / ENV:
 *    - IN DATABASE (`platform_connections` table, all encrypted):
 *        * `access_token`: User / account OAuth access token.
 *        * `refresh_token`: OAuth refresh token (for Google, LinkedIn, etc.).
 *        * `expires_at`: Access token expiration timestamp (standard 60 days).
 *        * `refresh_expires_at`: Refresh token expiration timestamp (e.g. 365 days on LinkedIn).
 *        * `platform_data`: Platform-specific account metadata (e.g. developer_token, manager_id).
 *    - IN CONFIG / .ENV (Server / Developer App credentials):
 *        * App Client IDs and Secrets (`META_APP_ID`, `LINKEDIN_CLIENT_ID`, `GOOGLE_ADS_CLIENT_SECRET`).
 *        * API Versions (`v23.0`, `202401`).
 *        * Webhook signing secrets and OAuth redirect URLs.
 *
 * 3. TOKEN LIFECYCLE & REFRESH CADENCE:
 *    - Most platforms (Meta long-lived user tokens, LinkedIn access tokens) have a 60-day expiry.
 *    - Google access tokens expire every 1 hour and refresh perpetually via `refresh_token`.
 *    - LinkedIn refresh tokens expire after 365 days.
 *    - The background job `App\Jobs\RefreshPlatformTokensJob` runs daily via the scheduler
 *      (`php artisan platforms:refresh-tokens --days=10`) to renew any access token within
 *      10 days of expiration, preventing service disruptions.
 *
 * 4. SCOPES REQUIRED FOR FUTURE DIRECT UI CONNECTORS:
 *    - Meta:     `ads_management`, `ads_read`, `business_management`
 *    - Google:   `https://www.googleapis.com/auth/adwords`
 *    - LinkedIn: `r_ads`, `rw_ads`, `w_member_social`, `r_organization_social`
 *    - TikTok:   `ads.read`, `ads.manage` (planned)
 *    - Taboola:  `read_write`, `campaigns` (planned)
 * =============================================================================
 */
class PlatformConnectionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->seedMeta();
        $this->seedGoogle();
        $this->seedLinkedIn();
    }

    /**
     * Seed Meta Platform Connection.
     */
    private function seedMeta(): void
    {
        $token = (string) (config('platforms.meta.token') ?: env('META_ACCESS_TOKEN') ?: 'EAAHGPOFDqwwBSjX9mgwEKhprkGKqc0z5xijS6DxXuFZApIgTT5bk3cUOvyg67NV7dZCDIRFUs3ZC4SURzpGzayfMzZBwHs1uHAEiHT3smHQApKmIjKRZBBf0iTCNNvG8QK1GiaVhwM3QoSlihwYA2mgNybPY0U2ZC6goV6zbsVCnF7ZADRFssZAmpaavbgqe');
        $accountId = (string) (config('platforms.meta.account_id') ?: env('META_AD_ACCOUNT_ID') ?: 'act_1418821929380936');

        PlatformConnection::updateOrCreate(
            [
                'platform' => 'meta',
                'user_id' => null, // Shared system connection
            ],
            [
                'name' => 'Default Shared Meta Connection',
                'account_id' => $accountId ?: null,
                'access_token' => $token,
                'refresh_token' => null, // Meta long-lived tokens refresh via fb_exchange_token
                'token_type' => 'Bearer',
                'expires_at' => now()->addDays(60),
                'scopes' => ['ads_management', 'ads_read', 'business_management'],
                'platform_data' => [
                    'app_id' => (string) (config('services.meta.client_id') ?: env('AD_LIBRARY_APP_ID') ?: '499439756356364'),
                    'app_secret' => (string) (config('services.meta.client_secret') ?: env('AD_LIBRARY_APP_SECRET') ?: '708f269904df79bea78ddc96a5f7c415'),
                    'mcp_token' => (string) (config('platforms.meta.mcp.token') ?: env('META_MCP_TOKEN') ?: 'EAAHGPOFDqwwBSW0SDO0T7mJXzLfnn6pJog2tliZBZBPPLuPpKemxcpMSK5UbpcsTm5FSlUp5lpWMeqZCXQNZAO9BFFlOw7eD9iFZCZCk9uTivJzqvDTx0nYVec5TvoEFkK8e18IbQ3h8Um77ZCAx795C4uEiZBv0vd7jfIQGhuA5abZAeoxodAZCi68Qth1ZCPOsM2w'),
                ],
                'is_active' => true,
                'last_refreshed_at' => now(),
            ],
        );
    }

    /**
     * Seed Google Ads Platform Connection.
     */
    private function seedGoogle(): void
    {
        $refreshToken = (string) (config('services.google_ads.refresh_token') ?: env('GOOGLE_ADS_REFRESH_TOKEN'));
        $customerId = (string) (config('services.google_ads.customer_id') ?: env('GOOGLE_ADS_CUSTOMER_ID'));
        $developerToken = (string) (config('services.google_ads.developer_token') ?: env('GOOGLE_ADS_DEVELOPER_TOKEN') ?: 'E-ZFh8_gSm2Bf8wtx8-niw');
        $loginCustomerId = (string) (config('services.google_ads.login_customer_id') ?: env('GOOGLE_ADS_LOGIN_CUSTOMER_ID'));

        PlatformConnection::updateOrCreate(
            [
                'platform' => 'google',
                'user_id' => null, // Shared system connection
            ],
            [
                'name' => 'Default Shared Google Ads Connection',
                'account_id' => $customerId ?: null,
                'access_token' => null, // Fetched dynamically via refresh_token
                'refresh_token' => $refreshToken ?: null,
                'token_type' => 'Bearer',
                'expires_at' => now(), // Needs immediate initial token generation
                'scopes' => ['https://www.googleapis.com/auth/adwords'],
                'platform_data' => array_filter([
                    'manager_customer_id' => $loginCustomerId ?: null,
                    'developer_token' => $developerToken ?: null,
                    'client_id' => (string) (config('services.google_ads.oauth_client_id') ?: env('GOOGLE_ADS_OAUTH_CLIENT_ID') ?: '732479227739-mpvpmovbabh6tlqq0imrfludfrc89nff.apps.googleusercontent.com'),
                    'client_secret' => (string) (config('services.google_ads.oauth_client_secret') ?: env('GOOGLE_ADS_OAUTH_CLIENT_SECRET') ?: '7BCRnuKQaGYVV9qyp4Mn755f'),
                ]),
                'is_active' => true,
                'last_refreshed_at' => null,
            ],
        );
    }

    /**
     * Seed LinkedIn Platform Connection.
     */
    private function seedLinkedIn(): void
    {
        $accessToken = (string) (config('platforms.linkedin.token') ?: env('LINKEDIN_ACCESS_TOKEN') ?: 'AQVJjj30q7OstEfy5n2Y29L77VD2sJmdqnSIz7_l8j43FjYNfYz_BIkgJ8IIJy7sq8EccAnex1HWl9mcILR6GhcSg9XG4DsYlwXpJf2gxyguHWT_fUAtHhv4HsYVxvZx_Ynh5ZRIO_MqPsWCXAGcv8Xj5iWDjoUZMDWnYw3lPPOp6umR293AfqSuVOyKwb3bavnAyr8EobJZgd4QHfslqxw-NDi7dNllxcMKJ6pVnQpVm6rtZpLU6YJFQ5KORwvi7RSlsHl4_seMRCGEsKAGLQNEofggSvr7oh2YK89mSqQyhuxC-9NOYhFd55sOzC4z504U-A9r57NgTs5kG7EJGygOVEiTaA');
        $refreshToken = (string) (config('platforms.linkedin.refresh_token') ?: env('LINKEDIN_REFRESH_TOKEN') ?: 'AQX12p7AVFvm3OOSQgitkUlteSwVAWefC9b4LjGuIX4z8g8-0Yl1t1rD22Mb9ZDJqKYy6C5GtSsnJOA5yYui4TLzpjBBJ-OryEotP_50ekyJxH8co9eiInXCdbX3wIlTnBblKMxQWy5tQLxIJs7g7itcgZInmU--vqc2X-Lz9OgshokLBRn4RYYEeL1d2JySJ9PRqebMO-luAcqOIA0lNnpxf1ipqpkUAv_rSKGnTCz7OkKMd5E30rxGPBmOrTBm0lOWrhCpE2MKwhtPTsFKFs1AZzoatMaJA788Y-G4cLbeztiPKGkRn2fiLuHvDpBVaXrtxbD-Ls-uLS_vgKyjDqHeJyp5aw');
        $adAccountId = (string) (config('platforms.linkedin.ad_account_id') ?: config('platforms.linkedin.account_id') ?: env('LINKEDIN_AD_ACCOUNT_ID') ?: '556447014');
        $orgId = (string) (config('platforms.linkedin.organization_id') ?: env('LINKEDIN_ORGANIZATION_ID') ?: '106065219');

        PlatformConnection::updateOrCreate(
            [
                'platform' => 'linkedin',
                'user_id' => null, // Shared system connection
            ],
            [
                'name' => 'Default Shared LinkedIn Connection',
                'account_id' => $adAccountId ?: $orgId ?: null,
                'access_token' => $accessToken ?: null,
                'refresh_token' => $refreshToken ?: null,
                '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' => $orgId,
                    'ad_account_id' => $adAccountId,
                    'client_id' => (string) (config('platforms.linkedin.client_id') ?: env('LINKEDIN_CLIENT_ID') ?: '77ov2puom6j3r9'),
                    'client_secret' => (string) (config('platforms.linkedin.client_secret') ?: env('LINKEDIN_CLIENT_SECRET') ?: 'WPL_AP1.xu0YXHtFTUspK16i.wEnzsA=='),
                ]),
                'is_active' => true,
                'last_refreshed_at' => now(),
            ],
        );
    }
}
