<?php

namespace Database\Seeders;

use App\Models\PostMetric;
use App\Models\Visitor;
use App\Models\SocialPost;
use App\Models\User;
use App\Models\Platform;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Faker\Factory as Faker;
use Carbon\Carbon;

class DemoAnalyticsSeeder extends Seeder
{
    /**
     * Run the database seeds for analytics data.
     */
    public function run(): void
    {
        $faker = Faker::create();

        // Enhance existing post metrics with time series data
        $this->createTimeSeriesMetrics();

        // Create platform performance data (analytics summary)
        $this->createPlatformPerformanceData($faker);
    }

    /**
     * Create time series metrics for posts
     */
    private function createTimeSeriesMetrics(): void
    {
        $posts = SocialPost::where('status', 1)->with('metrics')->get();
        $metricsCounter = 0;

        foreach ($posts as $post) {
            if (!$post->metrics()->exists()) {
                continue;
            }

            $baseMetrics = $post->metrics()->first();
            $createdAt = Carbon::parse($post->created_at);

            // Create daily metrics for the past 30 days from post creation
            for ($i = 1; $i <= 30; $i++) {
                $date = $createdAt->copy()->addDays($i);
                if ($date->isFuture()) break;

                $dailyGrowthFactor = $this->calculateDailyGrowthFactor($i);

                PostMetric::create([
                    'post_id' => $post->id,
                    'impressions' => (int)($baseMetrics->impressions * $dailyGrowthFactor),
                    'engagements' => (int)($baseMetrics->engagements * $dailyGrowthFactor),
                    'reactions' => (int)($baseMetrics->reactions * $dailyGrowthFactor),
                    'comments' => (int)($baseMetrics->comments * $dailyGrowthFactor),
                    'shares' => (int)($baseMetrics->shares * $dailyGrowthFactor),
                    'likes' => (int)($baseMetrics->likes * $dailyGrowthFactor),
                    'reach' => (int)($baseMetrics->reach * $dailyGrowthFactor),
                    'created_at' => $date,
                    'updated_at' => $date,
                ]);

                $metricsCounter++;
            }
        }

        $this->command->info("Created {$metricsCounter} time series metrics!");
    }

    /**
     * Calculate daily growth factor for metrics
     */
    private function calculateDailyGrowthFactor(int $day): float
    {
        // Simulate realistic growth pattern
        if ($day <= 1) return 0.1; // Day 1: 10% of total
        if ($day <= 3) return 0.4; // Peak engagement in first 3 days
        if ($day <= 7) return 0.7; // Good engagement first week
        if ($day <= 14) return 0.85; // Steady growth
        if ($day <= 21) return 0.95; // Near final numbers
        return 1.0; // Final numbers after 3 weeks
    }


    /**
     * Create platform performance analytics
     */
    private function createPlatformPerformanceData($faker): void
    {
        $platforms = Platform::all();
        $users = User::all();

        foreach ($platforms as $platform) {
            foreach ($users as $user) {
                // Create monthly performance summaries for the past 6 months
                for ($month = 0; $month < 6; $month++) {
                    $date = Carbon::now()->subMonths($month);

                    // This would typically be stored in a separate analytics table
                    // For demo purposes, we'll just add it to our output
                    $performanceData = [
                        'user_id' => $user->id,
                        'platform_id' => $platform->id,
                        'month' => $date->format('Y-m'),
                        'total_posts' => $faker->numberBetween(5, 50),
                        'total_impressions' => $faker->numberBetween(1000, 100000),
                        'total_engagements' => $faker->numberBetween(50, 5000),
                        'engagement_rate' => $faker->randomFloat(2, 0.5, 15.0),
                        'follower_growth' => $faker->numberBetween(-100, 500),
                        'reach' => $faker->numberBetween(800, 80000),
                        'top_performing_post_id' => null, // Would be actual post ID
                        'average_likes_per_post' => $faker->numberBetween(10, 1000),
                        'average_comments_per_post' => $faker->numberBetween(2, 100),
                        'average_shares_per_post' => $faker->numberBetween(1, 50),
                    ];
                }
            }
        }

        $this->command->info("Generated platform performance analytics data!");
    }
}