<?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 SegmentsTableSeeder 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 segments seeder.');
            return;
        }

        $now = Carbon::now();
        
        $segments = [
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Premium Customers',
                'description' => 'High-value customers with frequent purchases and high engagement',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(60)->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' => 'New Subscribers',
                'description' => 'Recently joined subscribers who need onboarding and welcome messages',
                'status' => 'active',
                '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' => 'VIP Members',
                'description' => 'Exclusive VIP members with special privileges and early access',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(50)->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' => 'WhatsApp Users',
                'description' => 'All customers who prefer WhatsApp as their communication channel',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(55)->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' => 'Telegram Community',
                'description' => 'telegram:-4957425114',
                'status' => 'active',
                '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' => 'Inactive Users',
                'description' => 'Users who have not engaged in the last 30 days',
                'status' => 'active',
                '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' => 'Sale Enthusiasts',
                'description' => 'Customers who frequently respond to sale and discount campaigns',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(48)->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' => 'Product Launch Followers',
                'description' => 'Users interested in new product announcements and launches',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(42)->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' => 'Feedback Providers',
                'description' => 'Engaged customers who regularly provide feedback and reviews',
                'status' => 'active',
                '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' => 'Newsletter Subscribers',
                'description' => 'Users subscribed to weekly newsletters and updates',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(52)->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' => 'Referral Program Members',
                'description' => 'Active participants in the referral and rewards program',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(33)->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' => 'Seasonal Shoppers',
                'description' => 'Customers who shop during holidays and special occasions',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(46)->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' => 'Archived Segment',
                'description' => 'Old segment no longer in active use',
                'status' => 'inactive',
                'created_at' => $now->copy()->subDays(90)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(60)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'name' => 'Beta Testers',
                'description' => 'Early adopters and beta testing participants',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(44)->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' => 'Loyalty Program',
                'description' => 'Members of the loyalty and rewards program',
                'status' => 'active',
                'created_at' => $now->copy()->subDays(58)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
        ];

        // Upsert segments
        DB::table('segments')->upsert($segments, ['unique_identifier'], [
            'user_id', 'name', 'description', 'status', 'updated_at'
        ]);

        // Create segment metadata
        $segmentMetas = [];
        foreach ($segments as $segment) {
            $segmentId = DB::table('segments')->where('unique_identifier', $segment['unique_identifier'])->value('id');
            
            if ($segmentId) {
                $channels = ['whatsapp', 'telegram'];
                $channel = $channels[array_rand($channels)];
                
                $segmentMetas[] = [
                    'owner_type' => 'Modules\MarketingBot\Entities\Segment',
                    'owner_id' => $segmentId,
                    'key' => 'channel',
                    'value' => $channel,
                    'type' => 'string',
                    'created_at' => $now->format('Y-m-d H:i:s'),
                    'updated_at' => $now->format('Y-m-d H:i:s'),
                ];
                
                // For Telegram segments (groups), add telegram_chat_id metadata
                if ($channel === 'telegram') {
                    // Generate a fake Telegram chat ID (negative for groups, typically)
                    $telegramChatId = '-' . $this->generateRandomNumberString(10);
                    
                    $segmentMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Segment',
                        'owner_id' => $segmentId,
                        'key' => 'telegram_chat_id',
                        'value' => $telegramChatId,
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                }
            }
        }

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

