<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\UserDetail;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class UserDetailSeeder extends Seeder
{
    public function run(): void
    {
        // Company management permissions
        $permissions = [
            'company.manager',
            'company.menu',
            'company.dashboard',
            'company.view',
            'company.create',
            'company.edit',
            'company.delete',
        ];

        foreach ($permissions as $permission) {
            $check = Permission::where('name', $permission)->first();

            if ($check) {
                continue;
            }
            Permission::create(['name' => $permission]);
        }

        $adminRole = Role::where('name', 'administrator')->first();
        if (! $adminRole) {
            $adminRole = Role::create(['name' => 'administrator']);
        }
        $adminRole->givePermissionTo(Permission::all());

        // Get existing users
        $existingUsers = User::all();
        $existingUserIds = $existingUsers->pluck('id')->toArray();

        // Company data templates
        $companyNames = [
            'TechCorp Solutions', 'Digital Innovations Inc', 'CodeWorks Ltd', 'DevPro Technologies',
            'SmartSoft Systems', 'FutureTech Labs', 'WebCraft Studio', 'AppDev Masters',
            'CloudTech Solutions', 'DataFlow Systems', 'CyberSecure Corp', 'AITech Innovations',
            'MobileDev Pro', 'GameDev Studio', 'FinTech Solutions', 'HealthTech Inc',
            'EdTech Innovations', 'GreenTech Systems', 'BlockChain Corp', 'IoT Solutions Ltd',
            'RoboTech Labs', 'VR Innovations', 'AR Solutions', 'ML Systems Corp',
            'BigData Analytics', 'Quantum Computing', 'Neural Networks Inc', 'DeepTech Labs',
            'Sakura Technologies', 'Toyota Software', 'Honda Digital', 'Sony Innovations',
            'NTT Solutions', 'Rakuten Tech', 'SoftBank Digital', 'Mitsubishi Systems',
            'Panasonic Labs', 'Sharp Technologies', 'Fujitsu Solutions', 'NEC Innovations',
            'Hitachi Digital', 'Toshiba Tech', 'Canon Software', 'Nikon Systems',
            'Yamaha Digital', 'Mazda Tech', 'Subaru Software', 'Nissan Innovations',
            'Casio Systems', 'Seiko Technologies', 'Citizen Digital', 'Bandai Labs',
        ];

        $descriptions = [
            'A leading software development company specializing in enterprise solutions with over 10 years of experience.',
            'Innovative technology company focused on digital transformation and cloud-native applications.',
            'Expert team delivering cutting-edge web and mobile applications for global clients.',
            'Full-stack development company with expertise in modern frameworks and scalable architectures.',
            'Specialized in AI and machine learning solutions for various industries.',
            'Creative digital agency combining design excellence with technical expertise.',
            'Enterprise software solutions provider with strong focus on security and performance.',
            'Mobile-first development company creating award-winning applications.',
            'Cloud infrastructure and DevOps specialists helping businesses scale efficiently.',
            'Data analytics and business intelligence solutions provider.',
            'Cybersecurity experts protecting digital assets with advanced technologies.',
            'Fintech solutions provider revolutionizing financial services through technology.',
            'Healthcare technology company improving patient care through digital solutions.',
            'Educational technology platform enhancing learning experiences worldwide.',
            'Sustainable technology solutions for environmental challenges.',
            'Blockchain and cryptocurrency development specialists.',
            'Internet of Things solutions connecting the physical and digital worlds.',
            'Robotics and automation solutions for industrial applications.',
            'Virtual and augmented reality experiences for various industries.',
            'Machine learning and neural network solutions provider.',
        ];

        $technologies = [
            ['PHP', 'Laravel', 'Vue.js', 'MySQL', 'AWS'],
            ['JavaScript', 'React', 'Node.js', 'MongoDB', 'Docker'],
            ['Python', 'Django', 'PostgreSQL', 'Redis', 'Kubernetes'],
            ['Java', 'Spring Boot', 'Angular', 'Oracle', 'Jenkins'],
            ['C#', '.NET Core', 'Azure', 'SQL Server', 'React'],
            ['Go', 'Gin', 'Vue.js', 'Redis', 'GCP'],
            ['Ruby', 'Rails', 'PostgreSQL', 'Sidekiq', 'Heroku'],
            ['Swift', 'iOS', 'Objective-C', 'Firebase', 'TestFlight'],
            ['Kotlin', 'Android', 'Room', 'Retrofit', 'Dagger'],
            ['Flutter', 'Dart', 'Firebase', 'GraphQL', 'AWS'],
            ['React Native', 'TypeScript', 'Expo', 'Apollo', 'Fastlane'],
            ['Unity', 'C#', 'Blender', 'Photon', 'Steam'],
            ['Unreal Engine', 'C++', 'Blueprint', 'Perforce', 'Wwise'],
            ['TensorFlow', 'PyTorch', 'Scikit-learn', 'Jupyter', 'Pandas'],
            ['Hadoop', 'Spark', 'Kafka', 'Elasticsearch', 'Tableau'],
            ['Solidity', 'Web3.js', 'Ethereum', 'IPFS', 'Truffle'],
            ['Rust', 'WebAssembly', 'Tokio', 'Actix', 'Serde'],
            ['Elixir', 'Phoenix', 'OTP', 'GenServer', 'LiveView'],
            ['Scala', 'Play Framework', 'Akka', 'Kafka', 'Cassandra'],
            ['DevOps', 'Terraform', 'Ansible', 'Prometheus', 'Grafana'],
        ];

        $tags = [
            ['ISO27001 Certified', 'Quick Response', 'Professional Team'],
            ['Agile Methodology', 'DevOps Culture', 'Cloud Expert'],
            ['24/7 Support', 'Scalable Solutions', 'Security First'],
            ['Mobile Specialists', 'UX/UI Excellence', 'Performance Optimized'],
            ['Full-stack Development', 'API Integration', 'Database Design'],
            ['Machine Learning', 'Data Science', 'AI Solutions'],
            ['Blockchain Expert', 'Cryptocurrency', 'Smart Contracts'],
            ['E-commerce Solutions', 'Payment Integration', 'Inventory Management'],
            ['Healthcare Compliance', 'HIPAA Certified', 'Medical Software'],
            ['Financial Services', 'Banking Solutions', 'Regulatory Compliance'],
            ['Gaming Industry', 'Entertainment Apps', 'Real-time Systems'],
            ['IoT Development', 'Embedded Systems', 'Hardware Integration'],
            ['AR/VR Development', 'Immersive Experiences', '3D Modeling'],
            ['Startup Friendly', 'Rapid Prototyping', 'MVP Development'],
            ['Enterprise Grade', 'High Availability', 'Load Balancing'],
        ];

        $strengths = [
            [
                ['title' => 'Technical Excellence', 'description' => 'Deep expertise in cutting-edge technologies and best practices'],
                ['title' => 'Agile Development', 'description' => 'Fast delivery with iterative approach and continuous feedback'],
            ],
            [
                ['title' => 'Industry Experience', 'description' => 'Proven track record across multiple industries and domains'],
                ['title' => 'Quality Assurance', 'description' => 'Comprehensive testing and quality control processes'],
            ],
            [
                ['title' => 'Scalable Architecture', 'description' => 'Building solutions that grow with your business needs'],
                ['title' => '24/7 Support', 'description' => 'Round-the-clock technical support and maintenance'],
            ],
            [
                ['title' => 'Security Focus', 'description' => 'Enterprise-grade security measures and compliance standards'],
                ['title' => 'Cost Effective', 'description' => 'Optimal solutions that maximize ROI and minimize costs'],
            ],
        ];

        $addresses = [
            'Tokyo Tech Tower, Shibuya, Tokyo, Japan',
            'Osaka Business Park, Osaka, Japan',
            'Yokohama Innovation Center, Kanagawa, Japan',
            'Kyoto Software Hub, Kyoto, Japan',
            'Nagoya Tech District, Aichi, Japan',
            'Sapporo Digital Center, Hokkaido, Japan',
            'Fukuoka Innovation Zone, Fukuoka, Japan',
            'Sendai Technology Park, Miyagi, Japan',
            'Silicon Valley Office, California, USA',
            'Austin Tech Hub, Texas, USA',
            'Seattle Innovation Center, Washington, USA',
            'Boston Technology District, Massachusetts, USA',
            'New York Digital Center, New York, USA',
            'London Tech Quarter, United Kingdom',
            'Berlin Innovation Lab, Germany',
            'Amsterdam Digital Hub, Netherlands',
            'Stockholm Tech Center, Sweden',
            'Helsinki Innovation District, Finland',
            'Singapore Tech Park, Singapore',
            'Sydney Innovation Hub, Australia',
        ];

        $branches = [
            [['name' => 'Ho Chi Minh Branch', 'address' => 'District 1, Ho Chi Minh City, Vietnam']],
            [['name' => 'Hanoi Office', 'address' => 'Ba Dinh District, Hanoi, Vietnam']],
            [['name' => 'Da Nang Center', 'address' => 'Hai Chau District, Da Nang, Vietnam']],
            [
                ['name' => 'Tokyo Branch', 'address' => 'Shinjuku, Tokyo, Japan'],
                ['name' => 'Osaka Office', 'address' => 'Namba, Osaka, Japan'],
            ],
            [
                ['name' => 'US West Coast', 'address' => 'San Francisco, CA, USA'],
                ['name' => 'US East Coast', 'address' => 'New York, NY, USA'],
            ],
        ];

        $hourlyRates = [
            '$25 - $40/hour',
            '$30 - $50/hour',
            '$40 - $60/hour',
            '$50 - $80/hour',
            '$60 - $100/hour',
            '$350,000 - $450,000 VND/person/month',
            '$400,000 - $600,000 VND/person/month',
            '$500,000 - $750,000 VND/person/month',
            '$600,000 - $900,000 VND/person/month',
            '$800,000 - $1,200,000 VND/person/month',
        ];

        $leaders = [
            ['name' => 'Tanaka Hiroshi', 'position' => 'CEO'],
            ['name' => 'Sato Yuki', 'position' => 'CTO'],
            ['name' => 'Suzuki Kenji', 'position' => 'CEO'],
            ['name' => 'Watanabe Akiko', 'position' => 'Founder & CEO'],
            ['name' => 'Ito Masaki', 'position' => 'President'],
            ['name' => 'Yamamoto Rei', 'position' => 'CEO'],
            ['name' => 'Nakamura Takeshi', 'position' => 'Managing Director'],
            ['name' => 'Kobayashi Yui', 'position' => 'CEO'],
            ['name' => 'Sasaki Daiki', 'position' => 'Founder'],
            ['name' => 'Kato Emiko', 'position' => 'CEO & Co-founder'],
            ['name' => 'John Smith', 'position' => 'CEO'],
            ['name' => 'Sarah Johnson', 'position' => 'Founder & CTO'],
            ['name' => 'Michael Chen', 'position' => 'President'],
            ['name' => 'Emily Davis', 'position' => 'CEO'],
            ['name' => 'David Wilson', 'position' => 'Managing Director'],
        ];

        // Create 100 company records
        for ($i = 0; $i < 100; $i++) {
            $hasUser = $i < 30 && ! empty($existingUserIds); // First 30 companies get users
            $userId = $hasUser ? $existingUserIds[array_rand($existingUserIds)] : null;

            // Remove used user ID to avoid duplicates
            if ($userId) {
                $existingUserIds = array_diff($existingUserIds, [$userId]);
            }

            $type = rand(1, 3); // Company, Software Team, or Freelancer
            $companyName = $companyNames[array_rand($companyNames)];
            $shortName = explode(' ', $companyName)[0];
            $leader = $leaders[array_rand($leaders)];
            $tech = $technologies[array_rand($technologies)];
            $companyTags = $tags[array_rand($tags)];
            $companyStrengths = $strengths[array_rand($strengths)];
            $branch = $branches[array_rand($branches)];

            UserDetail::create([
                'user_id'                        => $userId,
                'type'                           => $type,
                'phone'                          => '+' . rand(81, 84) . rand(10000000, 99999999),
                'business_email'                 => strtolower(str_replace(' ', '', $shortName)) . '@company.com',
                'company_short_name'             => $shortName,
                'company_full_name'              => $companyName . ' Co., Ltd.',
                'company_description'            => $descriptions[array_rand($descriptions)],
                'rating'                         => round(rand(35, 50) / 10, 1), // 3.5 to 5.0
                'tags'                           => json_encode($companyTags),
                'employee_count'                 => rand(5, 500),
                'engineer_count'                 => rand(3, 300),
                'n1_japanese_count'              => rand(0, 50),
                'established_year'               => rand(2010, 2023),
                'japanese_companies_performance' => rand(0, 25),
                'leader_name'                    => $leader['name'],
                'leader_position'                => $leader['position'],
                'establishment_date'             => now()->subYears(rand(1, 13))->format('Y-m-d'),
                'charter_capital'                => rand(1000000, 50000000) * 1000,
                'estimated_value'                => rand(5000000, 200000000) * 1000,
                'headquarters_address'           => $addresses[array_rand($addresses)],
                'branches'                       => json_encode($branch),
                'status'                         => rand(0, 2),
                'hourly_rate_range'              => $hourlyRates[array_rand($hourlyRates)],
                'key_technologies'               => json_encode($tech),
                'strengths'                      => json_encode($companyStrengths),
                'article_link'                   => rand(0, 1) ? 'https://example.com/company/' . strtolower(str_replace(' ', '-', $companyName)) : null,
            ]);
        }

        $this->command->info('100 company records created successfully!');
    }
}
