<?php

namespace Database\Seeders;

use App\Enums\StatusEnum;
use App\Models\SocialAccount;
use App\Models\Platform;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Faker\Factory as Faker;

class DemoSocialAccountSeeder extends Seeder
{
    /**
     * Run the database seeds for social accounts.
     */
    public function run(): void
    {
        $faker = Faker::create();

        // Get all platforms
        $platforms = Platform::where('status', StatusEnum::true->status())->get();

        // Get all users with their workspaces
        $users = User::with('currentWorkspace')->get();

        if ($platforms->isEmpty() || $users->isEmpty()) {
            $this->command->warn('Please run PlatformSeeder and DemoUserSeeder first!');
            return;
        }

        $accountNames = [
            'facebook' => ['Business Page', 'Community Group', 'Brand Page', 'Product Page', 'Event Page', 'Local Business', 'Entertainment', 'News Media', 'Sports Team', 'Non-Profit'],
            'instagram' => ['Fashion Blog', 'Food & Travel', 'Fitness Journey', 'Art Gallery', 'Tech Reviews', 'Pet Lovers', 'Beauty Tips', 'Lifestyle', 'Photography', 'Music Band'],
            'twitter' => ['Tech News', 'Business Updates', 'Personal Brand', 'Commentary', 'Crypto Updates', 'Sports News', 'Politics', 'Entertainment', 'Science Facts', 'Humor & Memes'],
            'linkedin' => ['Company Page', 'Professional Profile', 'Recruitment', 'B2B Marketing', 'Thought Leadership', 'Industry News', 'Career Tips', 'Business Strategy', 'HR Updates', 'Tech Innovation'],
            'youtube' => ['Vlog Channel', 'Tutorial Channel', 'Gaming Channel', 'Music Channel', 'News Channel', 'Educational', 'Comedy Skits', 'Product Reviews', 'Cooking Show', 'DIY Crafts'],
            'pinterest' => ['DIY Ideas', 'Recipe Collection', 'Fashion Board', 'Home Decor', 'Travel Plans', 'Wedding Ideas', 'Fitness Tips', 'Art & Design', 'Photography', 'Gardening'],
            'tiktok' => ['Dance Videos', 'Comedy Skits', 'Life Hacks', 'Food Recipes', 'Fashion Tips', 'Pet Videos', 'Education', 'Fitness', 'Art Process', 'Tech Tips'],
            'reddit' => ['Tech Community', 'Gaming Forum', 'News Discussion', 'Memes & Humor', 'Science Topics', 'Movies & TV', 'Books & Literature', 'Fitness Community', 'Food & Cooking', 'Travel Stories'],
            'whatsapp' => ['Business Chat', 'Customer Support', 'Team Updates', 'Marketing', 'Sales Team', 'Community Group', 'News Updates', 'Event Planning', 'Family Business', 'Local Services'],
            'telegram' => ['News Channel', 'Community Group', 'Tech Updates', 'Trading Signals', 'Educational', 'Entertainment', 'Business Network', 'Support Group', 'Local News', 'Event Updates'],
        ];

        $accountCounter = 0;

        foreach ($users as $user) {
            // Each user gets 10-15 social accounts across different platforms
            $numAccounts = rand(10, 15);
            $userPlatforms = $platforms->random(min($numAccounts, $platforms->count()));

            foreach ($userPlatforms as $platform) {
                $platformSlug = $platform->slug;
                $accountTypeNames = $accountNames[$platformSlug] ?? ['Default Account'];
                $accountName = $faker->randomElement($accountTypeNames);

                $accountCounter++;

                $followers = $this->generateFollowers($platformSlug);

                SocialAccount::create([
                    'uid' => Str::uuid(),
                    'platform_id' => $platform->id,
                    'workspace_id' => $user->current_workspace_id ?? $user->currentWorkspace?->id,
                    'user_id' => $user->id,
                    'label' => $accountName . ' - ' . $faker->company,
                    'name' => $faker->userName . '_' . $platformSlug,
                    'account_id' => $faker->uuid,
                    'account_information' => json_encode([
                        'profile_url' => 'https://' . $platformSlug . '.com/' . $faker->userName,
                        'bio' => $faker->sentence(10),
                        'verified' => $faker->boolean(30),
                        'created_date' => $faker->dateTimeBetween('-3 years', '-6 months')->format('Y-m-d'),
                    ]),
                    'followers' => $followers,
                    'status' => $faker->randomElement([StatusEnum::true->status(), StatusEnum::true->status(), StatusEnum::false->status()]),
                    'is_official' => $faker->boolean(20) ? StatusEnum::true->status() : StatusEnum::false->status(),
                    'is_connected' => StatusEnum::true->status(),
                    'account_type' => $faker->numberBetween(1, 3),
                    'details' => json_encode([
                        'engagement_rate' => $faker->randomFloat(2, 0.5, 15.0),
                        'posts_count' => $faker->numberBetween(10, 5000),
                        'average_likes' => $faker->numberBetween(10, 10000),
                        'category' => $faker->randomElement(['Business', 'Personal', 'Creator', 'Media', 'Brand']),
                    ]),
                    'token' => Str::random(60),
                    'access_token_expire_at' => now()->addMonths(3),
                    'refresh_token' => Str::random(60),
                    'refresh_token_expire_at' => now()->addMonths(6),
                    'created_at' => $faker->dateTimeBetween('-1 year', 'now'),
                    'updated_at' => now(),
                ]);
            }
        }

        $this->command->info("Created {$accountCounter} demo social accounts!");
    }

    /**
     * Generate realistic follower counts based on platform
     */
    private function generateFollowers(string $platform): int
    {
        $ranges = [
            'facebook' => [100, 50000],
            'instagram' => [500, 100000],
            'twitter' => [200, 75000],
            'linkedin' => [100, 25000],
            'youtube' => [1000, 500000],
            'pinterest' => [50, 10000],
            'tiktok' => [1000, 250000],
            'reddit' => [10, 5000],
            'whatsapp' => [50, 1000],
            'telegram' => [100, 50000],
        ];

        $range = $ranges[$platform] ?? [100, 10000];

        // Create more realistic distribution (more smaller accounts)
        $random = rand(1, 100);
        if ($random <= 60) {
            // 60% small accounts
            return rand($range[0], (int)($range[1] * 0.1));
        } elseif ($random <= 85) {
            // 25% medium accounts
            return rand((int)($range[1] * 0.1), (int)($range[1] * 0.5));
        } else {
            // 15% large accounts
            return rand((int)($range[1] * 0.5), $range[1]);
        }
    }
}