<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('product_views', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->string('ip_address', 45)->nullable();
            $table->timestamp('created_at')->nullable();
        });

        // Copy existing views from the 'product' table to 'product_views' table spread over the last 30 days
        try {
            $products = DB::table('product')->where('views', '>', 0)->get();
            foreach ($products as $product) {
                $totalViews = $product->views;
                // Limit to 100 views per product to prevent excessive migration time
                $viewsToMigrate = min($totalViews, 100);
                for ($i = 0; $i < $viewsToMigrate; $i++) {
                    $randomDaysAgo = rand(0, 30);
                    $viewTime = Carbon::now()->subDays($randomDaysAgo)->subHours(rand(0, 23))->subMinutes(rand(0, 59));
                    DB::table('product_views')->insert([
                        'product_id' => $product->id,
                        'ip_address' => '127.0.0.1',
                        'created_at' => $viewTime,
                    ]);
                }
            }
        } catch (\Throwable $e) {
            // Silence any errors during data migration so that the table is still created
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('product_views');
    }
};
