<?php

namespace Modules\Dummy\Database\Seeders\Modules\MarketingBot\versions\v6_4_0;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Carbon\Carbon;

class ContactsTableSeeder extends Seeder
{
    /**
     * Generate a random number string of specified length
     *
     * @param int $length
     * @return string
     */
    private function generateRandomNumberString(int $length): string
    {
        $number = '';
        for ($i = 0; $i < $length; $i++) {
            $number .= mt_rand(0, 9);
        }
        return $number;
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $demoUser = DB::table('users')->where('email', 'user@techvill.net')->first();

        if (!$demoUser) {
            $this->command->warn('Demo user (user@techvill.net) not found. Skipping contacts seeder.');
            return;
        }

        $now = Carbon::now();
        
        // Generate random phone numbers and country codes for WhatsApp contacts
        $countryCodes = ['US', 'GB', 'CA', 'AU', 'DE', 'FR', 'IT', 'ES', 'NL', 'SE', 'NO', 'DK', 'FI', 'PL', 'CZ', 'AT', 'CH', 'BE', 'IE', 'PT'];
        
        $contacts = [
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'John Anderson',
                'phone' => $this->generateRandomNumberString(10),
                'country_code' => $countryCodes[array_rand($countryCodes)],
                'channel' => 'whatsapp',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(2)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(30)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Sarah Mitchell',
                'phone' => null,
                'country_code' => null,
                'channel' => 'telegram',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(1)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(25)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Michael Chen',
                'phone' => $this->generateRandomNumberString(10),
                'country_code' => $countryCodes[array_rand($countryCodes)],
                'channel' => 'whatsapp',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(5)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(40)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Emma Wilson',
                'phone' => null,
                'country_code' => null,
                'channel' => 'telegram',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(3)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(20)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'David Rodriguez',
                'phone' => $this->generateRandomNumberString(10),
                'country_code' => $countryCodes[array_rand($countryCodes)],
                'channel' => 'whatsapp',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(7)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(35)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Lisa Thompson',
                'phone' => null,
                'country_code' => null,
                'channel' => 'telegram',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(4)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(28)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Robert Kumar',
                'phone' => $this->generateRandomNumberString(10),
                'country_code' => $countryCodes[array_rand($countryCodes)],
                'channel' => 'whatsapp',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(6)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(45)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Sophie Martin',
                'phone' => null,
                'country_code' => null,
                'channel' => 'telegram',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(2)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(22)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'James Brown',
                'phone' => $this->generateRandomNumberString(10),
                'country_code' => $countryCodes[array_rand($countryCodes)],
                'channel' => 'whatsapp',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(8)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(38)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Maria Garcia',
                'phone' => null,
                'country_code' => null,
                'channel' => 'telegram',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(1)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(15)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Thomas Lee',
                'phone' => $this->generateRandomNumberString(10),
                'country_code' => $countryCodes[array_rand($countryCodes)],
                'channel' => 'whatsapp',
                'status' => 'inactive',
                'last_contacted_at' => $now->copy()->subDays(45)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(60)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(45)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Olivia White',
                'phone' => null,
                'country_code' => null,
                'channel' => 'telegram',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(3)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(18)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Daniel Kim',
                'phone' => $this->generateRandomNumberString(10),
                'country_code' => $countryCodes[array_rand($countryCodes)],
                'channel' => 'whatsapp',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(4)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(32)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Isabella Taylor',
                'phone' => null,
                'country_code' => null,
                'channel' => 'telegram',
                'status' => 'inactive',
                'last_contacted_at' => $now->copy()->subDays(50)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(70)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(50)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'William Johnson',
                'phone' => $this->generateRandomNumberString(10),
                'country_code' => $countryCodes[array_rand($countryCodes)],
                'channel' => 'whatsapp',
                'status' => 'active',
                'last_contacted_at' => $now->copy()->subDays(2)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(27)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
        ];

        // Upsert contacts
        DB::table('contacts')->upsert($contacts, ['unique_identifier'], [
            'user_id', 'name', 'phone', 'country_code', 'channel', 'status', 'last_contacted_at', 'updated_at'
        ]);

        // Get segments for linking contacts to segments
        $segmentIds = DB::table('segments')
            ->where('user_id', $demoUser->id)
            ->pluck('id')
            ->toArray();

        // Create contact metadata
        $contactMetas = [];
        foreach ($contacts as $index => $contact) {
            $contactId = DB::table('contacts')->where('unique_identifier', $contact['unique_identifier'])->value('id');
            
            if ($contactId) {
                // For Telegram contacts, add telegram_contact_id
                if ($contact['channel'] === 'telegram') {
                    // Generate a fake Telegram user ID (typically numeric)
                    $telegramContactId = $this->generateRandomNumberString(10);
                    
                    $contactMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Contact',
                        'owner_id' => $contactId,
                        'key' => 'telegram_contact_id',
                        'value' => $telegramContactId,
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                }

                // Add segment_ids metadata (contacts can belong to segments)
                // Randomly assign 0-2 segments to each contact
                if (!empty($segmentIds)) {
                    $assignedSegments = [];
                    $maxSegments = min(2, count($segmentIds));
                    $segmentCount = $maxSegments > 0 ? mt_rand(0, $maxSegments) : 0;
                    
                    if ($segmentCount > 0) {
                        $selectedSegments = array_rand($segmentIds, $segmentCount);
                        if (!is_array($selectedSegments)) {
                            $selectedSegments = [$selectedSegments];
                        }
                        
                        foreach ($selectedSegments as $segIndex) {
                            $assignedSegments[] = (string)$segmentIds[$segIndex];
                        }
                    }
                    
                    if (!empty($assignedSegments)) {
                        $contactMetas[] = [
                            'owner_type' => 'Modules\MarketingBot\Entities\Contact',
                            'owner_id' => $contactId,
                            'key' => 'segment_ids',
                            'value' => json_encode($assignedSegments),
                            'type' => 'array',
                            'created_at' => $now->format('Y-m-d H:i:s'),
                            'updated_at' => $now->format('Y-m-d H:i:s'),
                        ];
                    }
                }
            }
        }

        if (!empty($contactMetas)) {
            DB::table('contact_metas')->upsert($contactMetas, ['owner_type', 'owner_id', 'key'], [
                'value', 'updated_at'
            ]);
        }
    }
}

