<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // First check if the sessions table exists
        if (!Schema::hasTable('sessions')) {
            // Create the sessions table if it doesn't exist (Laravel's default structure)
            Schema::create('sessions', function (Blueprint $table) {
                $table->string('id')->primary();
                $table->foreignId('user_id')->nullable()->index();
                $table->string('ip_address', 45)->nullable();
                $table->text('user_agent')->nullable();
                $table->text('payload');
                $table->integer('last_activity')->index();
            });
        }

        // Add device info columns to the sessions table
        Schema::table('sessions', function (Blueprint $table) {
            if (!Schema::hasColumn('sessions', 'device_type')) {
                $table->string('device_type')->nullable()->after('user_agent');
            }
            if (!Schema::hasColumn('sessions', 'device_name')) {
                $table->string('device_name')->nullable()->after('device_type');
            }
            if (!Schema::hasColumn('sessions', 'browser')) {
                $table->string('browser')->nullable()->after('device_name');
            }
            if (!Schema::hasColumn('sessions', 'platform')) {
                $table->string('platform')->nullable()->after('browser');
            }
            if (!Schema::hasColumn('sessions', 'location')) {
                $table->string('location')->nullable()->after('platform');
            }
            if (!Schema::hasColumn('sessions', 'country')) {
                $table->string('country')->nullable()->after('location');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('sessions', function (Blueprint $table) {
            $table->dropColumn([
                'device_type',
                'device_name',
                'browser',
                'platform',
                'location',
                'country'
            ]);
        });
    }
};