<?php

namespace Database\Seeders;

use App\Models\Group;
use App\Models\Number;
use App\Models\User;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class GroupAndNumberSeeder extends Seeder
{
    /**
     * Run the database seeds for 10 groups and 1000 numbers.
     *
     * @return void
     */
    public function run(): void
    {
        $faker = Faker::create('en_US');

        // Find primary user or fallback to ID 1
        $user = User::first();
        $userId = $user ? (int) $user->id : 1;

        $this->command?->info("Seeding groups and numbers for User ID: {$userId}...");

        $predefinedGroups = [
            [
                'name' => 'VIP Customers',
                'description' => 'High-priority premium customers for exclusive campaigns and rewards.',
                'color' => '#246bfd', // Blue
            ],
            [
                'name' => 'Marketing Leads',
                'description' => 'Prospective leads and inbound campaign inquiries.',
                'color' => '#10b981', // Emerald
            ],
            [
                'name' => 'Wholesale Buyers',
                'description' => 'Bulk purchasers and B2B distributor network.',
                'color' => '#f59e0b', // Amber
            ],
            [
                'name' => 'Retail Clients',
                'description' => 'Regular retail walk-in and e-commerce shoppers.',
                'color' => '#ef4444', // Red
            ],
            [
                'name' => 'Newsletter Subscribers',
                'description' => 'Subscribers opted-in for weekly promotional SMS and announcements.',
                'color' => '#8b5cf6', // Violet
            ],
            [
                'name' => 'Tech Support',
                'description' => 'Technical contacts and system maintenance alert recipients.',
                'color' => '#ec4899', // Pink
            ],
            [
                'name' => 'Event Attendees',
                'description' => 'Registered participants for upcoming workshops and webinars.',
                'color' => '#06b6d4', // Cyan
            ],
            [
                'name' => 'Internal Staff',
                'description' => 'Internal team members, managers, and field staff.',
                'color' => '#6366f1', // Indigo
            ],
            [
                'name' => 'Suppliers & Vendors',
                'description' => 'Raw material suppliers, logistics partners, and vendors.',
                'color' => '#14b8a6', // Teal
            ],
            [
                'name' => 'Promo Offers',
                'description' => 'Flash sale, discount, and holiday promo broadcast list.',
                'color' => '#f97316', // Orange
            ],
        ];

        $createdGroupIds = [];

        foreach ($predefinedGroups as $groupData) {
            $group = Group::updateOrCreate(
                [
                    'user_id' => $userId,
                    'name' => $groupData['name'],
                ],
                [
                    'description' => $groupData['description'],
                    'color' => $groupData['color'],
                ]
            );
            $createdGroupIds[] = $group->id;
        }

        $this->command?->info("Created/Updated " . count($createdGroupIds) . " groups successfully.");

        // Generate 1000 unique phone numbers distributed across the 10 groups
        $totalNumbers = 50;
        $prefixes = ['017', '013', '019', '014', '018', '016', '015'];
        $generatedPhones = [];
        $records = [];
        $now = now();

        $groupCount = count($createdGroupIds);
        $perGroup = (int) ceil($totalNumbers / $groupCount);

        $noteTemplates = [
            'Regular active customer',
            'Registered via mobile gateway',
            'Subscribed for promotional updates',
            'VIP tier member',
            'Direct referral contact',
            'Verified phone number',
            'Priority notification enabled',
            'Regional branch contact',
        ];

        $counter = 0;
        for ($i = 0; $i < $totalNumbers; $i++) {
            // Assign group in round-robin fashion for even distribution (100 numbers per group)
            $groupId = $createdGroupIds[$i % $groupCount];

            // Generate a unique 11-digit Bangladeshi mobile number
            do {
                $prefix = $faker->randomElement($prefixes);
//                $suffix = str_pad((string) $faker->numberBetween(10000000, 99999999), 6, '0', STR_PAD_LEFT);
                $suffix = str_pad((string) $faker->numberBetween(0, 999999), 6, '0', STR_PAD_LEFT);
                $phone = $prefix . $suffix;
            } while (isset($generatedPhones[$phone]));

            $generatedPhones[$phone] = true;

            $records[] = [
                'user_id' => $userId,
                'group_id' => $groupId,
                'name' => $faker->name(),
                'number' => $phone,
                'notes' => $faker->optional(0.7)->randomElement($noteTemplates),
                'created_at' => $now,
                'updated_at' => $now,
            ];
            $counter++;
        }

        // Insert in batches of 250 for speed and low memory usage
        $chunks = array_chunk($records, 250);
        foreach ($chunks as $chunkIndex => $chunk) {
            DB::table('numbers')->insert($chunk);
            $this->command?->info("Inserted batch " . ($chunkIndex + 1) . " (" . count($chunk) . " contacts)...");
        }

        $groupGP = Group::updateOrCreate(
            ['user_id' => $userId, 'name' => 'OWN Group GP'],
            ['description' => 'No Description', 'color' => '#06b6d4']
        );
        $groupBL = Group::updateOrCreate(
            ['user_id' => $userId, 'name' => 'OWN Group BL'],
            ['description' => 'No Description', 'color' => '#06b6d4']
        );

        $numberGP = ['01788208626','01788208626','01788208626','01788208626','01788208626'];
        $numberBL = ['01946492622','01946492622','01946492622','01946492622','01946492622'];
        foreach ($numberGP as $number) {
            $recordss[] = [
                'user_id' => $userId,
                'group_id' => $groupGP->id,
                'name' => $faker->name(),
                'number' => $number,
                'notes' => $faker->optional(0.7)->randomElement($noteTemplates),
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }
        foreach ($numberBL as $number) {
            $recordss[] = [
                'user_id' => $userId,
                'group_id' => $groupBL->id,
                'name' => $faker->name(),
                'number' => $number,
                'notes' => $faker->optional(0.7)->randomElement($noteTemplates),
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        DB::table('numbers')->insert($recordss);

        $this->command?->info("Successfully seeded {$counter} numbers across {$groupCount} groups!");
    }
}
