<?php

namespace Database\Seeders;

use App\Enums\StatusEnum;
use App\Models\Platform;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use App\Helpers\InstallationLogger;
use Exception;

class PlatformSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        InstallationLogger::info('PlatformSeeder: Starting platform seeding');

        // Hardcode platforms directly to ensure they're always seeded
        $platforms = [
            'facebook' => [
                'name' => 'Facebook',
                'icon' => 'facebook',
                'url' => 'https://facebook.com',
                'credential' => [
                    'client_id' => 'your-facebook-app-id',
                    'client_secret' => 'your-facebook-app-secret',
                    'app_version' => 'v18.0',
                    'graph_api_url' => 'https://graph.facebook.com',
                    'group_url' => 'https://www.facebook.com/groups',
                ],
                'is_integrated' => StatusEnum::true->status(),
                'is_feature' => StatusEnum::true->status(),
                'view_option' => StatusEnum::true->status()
            ],
            'instagram' => [
                'name' => 'Instagram',
                'icon' => 'instagram',
                'url' => 'https://instagram.com',
                'credential' => [
                    'client_id' => 'your-instagram-app-id',
                    'client_secret' => 'your-instagram-app-secret',
                    'app_version' => 'v18.0',
                    'graph_api_url' => 'https://graph.facebook.com'
                ],
                'is_integrated' => StatusEnum::true->status(),
                'view_option' => StatusEnum::true->status(),
                'is_feature' => StatusEnum::true->status()
            ],
            'twitter' => [
                'name' => 'Twitter',
                'icon' => 'twitter',
                'url' => 'https://twitter.com',
                'credential' => [
                    'api_key' => '-',
                    'api_secret' => '-',
                    'access_token' => '-',
                    'access_token_secret' => '-',
                    'client_id' => 'your-twitter-client-id',
                    'client_secret' => 'your-twitter-client-secret',
                    'app_version' => 'v2'
                ],
                'is_integrated' => StatusEnum::true->status(),
                'unofficial' => StatusEnum::false->status(),
                'is_feature' => StatusEnum::true->status()
            ],
            'linkedin' => [
                'name' => 'LinkedIn',
                'icon' => 'linkedin',
                'url' => 'https://linkedin.com',
                'credential' => [
                    'client_id' => 'your-linkedin-client-id',
                    'client_secret' => 'your-linkedin-client-secret',
                ],
                'is_integrated' => StatusEnum::true->status(),
                'is_feature' => StatusEnum::true->status()
            ],
            'tiktok' => [
                'name' => 'TikTok',
                'icon' => 'tiktok',
                'url' => 'https://tiktok.com',
                'credential' => [
                    'client_key' => 'your-tiktok-client-key',
                    'client_secret' => 'your-tiktok-client-secret',
                ],
                'is_integrated' => StatusEnum::true->status(),
                'is_feature' => StatusEnum::true->status()
            ],
            'youtube' => [
                'name' => 'YouTube',
                'icon' => 'youtube',
                'url' => 'https://youtube.com',
                'credential' => [
                    'client_id' => 'your-youtube-client-id',
                    'client_secret' => 'your-youtube-client-secret',
                ],
                'is_integrated' => StatusEnum::true->status(),
                'is_feature' => StatusEnum::true->status()
            ],
            'threads' => [
                'name' => 'Threads',
                'icon' => 'threads',
                'url' => 'https://threads.net',
                'credential' => [
                    'client_id' => 'your-threads-client-id',
                    'client_secret' => 'your-threads-client-secret',
                ],
                'is_integrated' => StatusEnum::true->status(),
                'is_feature' => StatusEnum::true->status()
            ],
        ];

        InstallationLogger::info('PlatformSeeder: Will attempt to seed ' . count($platforms) . ' platforms');

        // Check existing platforms first
        $existingPlatforms = Platform::pluck('name', 'slug')->toArray();
        InstallationLogger::info('PlatformSeeder: Found ' . count($existingPlatforms) . ' existing platforms in database');

        $successCount = 0;
        $skipCount = 0;
        $errorCount = 0;

        foreach ($platforms as $slug => $platform) {
            $platformSlug = Str::slug($slug);

            try {
                InstallationLogger::info("PlatformSeeder: Processing platform - {$platform['name']} (slug: {$platformSlug})");

                // Check if platform already exists (by slug or name)
                $existingPlatform = Platform::where('slug', $platformSlug)
                    ->orWhere('name', $platform['name'])
                    ->first();

                if ($existingPlatform) {
                    InstallationLogger::info("PlatformSeeder: Platform {$platform['name']} already exists (ID: {$existingPlatform->id}), skipping");
                    $skipCount++;
                    continue;
                }

                // Double-check slug uniqueness
                $slugCount = Platform::where('slug', $platformSlug)->count();
                if ($slugCount > 0) {
                    InstallationLogger::warning("PlatformSeeder: Slug '{$platformSlug}' already exists, skipping {$platform['name']}");
                    $skipCount++;
                    continue;
                }

                // Create platform data with explicit uid
                $platformData = [
                    'uid' => Str::uuid(),
                    'name' => $platform['name'],
                    'slug' => $platformSlug,
                    'url' => $platform['url'] ?? 'https://example.com',
                    'icon' => $platform['icon'],
                    'configuration' => $platform['credential'],
                    'status' => $platform['status'] ?? StatusEnum::true->status(),
                    'is_feature' => $platform['is_feature'] ?? StatusEnum::false->status(),
                    'is_integrated' => $platform['is_integrated'] ?? StatusEnum::true->status(),
                    'view_option' => $platform['view_option'] ?? StatusEnum::false->status(),
                    'unofficial' => $platform['unofficial'] ?? StatusEnum::false->status(),
                ];

                InstallationLogger::debug("PlatformSeeder: Creating platform with data: " . json_encode($platformData, JSON_UNESCAPED_SLASHES));

                // Create platform using direct database insertion to avoid model events interference
                $newPlatform = new Platform();

                // Manually set all attributes to bypass model events
                $newPlatform->uid = $platformData['uid'];
                $newPlatform->name = $platformData['name'];
                $newPlatform->slug = $platformData['slug'];
                $newPlatform->url = $platformData['url'];
                $newPlatform->icon = $platformData['icon'];
                $newPlatform->configuration = $platformData['configuration'];
                $newPlatform->status = $platformData['status'];
                $newPlatform->is_feature = $platformData['is_feature'];
                $newPlatform->is_integrated = $platformData['is_integrated'];
                $newPlatform->view_option = $platformData['view_option'];
                $newPlatform->unofficial = $platformData['unofficial'];

                // Save without triggering events
                $newPlatform->saveQuietly();

                InstallationLogger::info("PlatformSeeder: Successfully created {$platform['name']} (ID: {$newPlatform->id})");
                $successCount++;

            } catch (Exception $e) {
                $errorCount++;
                InstallationLogger::error("PlatformSeeder: Failed to seed {$platform['name']}: " . $e->getMessage());
                InstallationLogger::error("PlatformSeeder: Error file: {$e->getFile()} line: {$e->getLine()}");
                InstallationLogger::debug("PlatformSeeder: Error trace: " . $e->getTraceAsString());

                // Continue with other platforms even if one fails
                continue;
            }
        }

        // Summary
        InstallationLogger::info("PlatformSeeder: Seeding completed - Success: {$successCount}, Skipped: {$skipCount}, Errors: {$errorCount}");

        // Verify final count
        $finalCount = Platform::count();
        InstallationLogger::info("PlatformSeeder: Total platforms in database after seeding: {$finalCount}");

        // Log all platform names for verification
        $allPlatforms = Platform::pluck('name', 'slug')->toArray();
        foreach ($allPlatforms as $slug => $name) {
            InstallationLogger::info("PlatformSeeder: Verified platform: {$name} (slug: {$slug})");
        }

        InstallationLogger::info('PlatformSeeder: Completed successfully');
    }
}
