<?php

namespace Database\Seeders;

use App\Models\Ad;
use App\Models\AnalyticsEvent;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Seeder;

class AnalyticsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get some users and ads
        $userIds = User::pluck('id')->toArray();
        $adIds = Ad::pluck('id')->toArray();

        if (empty($userIds) || empty($adIds)) {
            $this->command->info('No users or ads found. skipping analytics seeding.');
            return;
        }

        $events = [];
        $eventTypes = [
            'page_view' => 1000,
            'ad_viewed' => 500,
            'ad_clicked' => 100,
            'user_registration' => 20,
            'ad_posted' => 30,
            'message_sent' => 150,
        ];

        $browsers = ['Chrome', 'Firefox', 'Safari', 'Edge'];
        $devices = ['Desktop', 'Mobile', 'Tablet'];
        $countries = ['India', 'USA', 'UK', 'Canada', 'UAE'];
        $cities = ['Mumbai', 'Delhi', 'New York', 'London', 'Dubai'];

        // Generate data for last 30 days
        for ($i = 0; $i < 30; $i++) {
            $date = Carbon::now()->subDays($i);
            
            foreach ($eventTypes as $type => $count) {
                // Daily variance
                $dailyCount = rand((int)($count/40), (int)($count/20));

                for ($j = 0; $j < $dailyCount; $j++) {
                    $userId = rand(0, 10) > 7 ? $userIds[array_rand($userIds)] : null; // 30% authenticated
                    $adId = in_array($type, ['ad_viewed', 'ad_clicked']) ? $adIds[array_rand($adIds)] : null;
                    
                    $events[] = [
                        'event_type' => $type,
                        'user_id' => $userId,
                        'session_id' => \Str::uuid(),
                        'ip_address' => '192.168.1.' . rand(1, 255),
                        'user_agent' => 'Mozilla/5.0 ...',
                        'device_type' => $devices[array_rand($devices)],
                        'browser' => $browsers[array_rand($browsers)],
                        'os' => 'Windows',
                        'country' => $countries[array_rand($countries)],
                        'city' => $cities[array_rand($cities)],
                        'page_url' => $adId ? "/ads/{$adId}" : "/home",
                        'referrer' => 'google.com',
                        'event_data' => json_encode($adId ? ['ad_id' => $adId] : []),
                        'created_at' => $date->copy()->addMinutes(rand(0, 1440)),
                        'updated_at' => $date->copy()->addMinutes(rand(0, 1440)),
                    ];
                }
            }
        }

        // Insert in chunks
        foreach (array_chunk($events, 500) as $chunk) {
            AnalyticsEvent::insert($chunk);
        }
    }
}
