<?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
    {
        $missingColumns = collect([
            'google_id',
            'avatar_url',
            'role',
            'questionnaire_completed_at',
            'access_unlocked_at',
            'resume_uploaded_at',
            'resume_analyzed_at',
            'profile_completed_at',
            'last_login_at',
        ])->filter(fn (string $column): bool => ! Schema::hasColumn('users', $column));

        if ($missingColumns->isEmpty()) {
            return;
        }

        Schema::table('users', function (Blueprint $table) use ($missingColumns): void {
            if ($missingColumns->contains('google_id')) {
                $table->string('google_id')->nullable()->unique()->after('id');
            }

            if ($missingColumns->contains('avatar_url')) {
                $table->string('avatar_url', 2048)->nullable()->after('password');
            }

            if ($missingColumns->contains('role')) {
                $table->string('role')->default('user')->index()->after('avatar_url');
            }

            if ($missingColumns->contains('questionnaire_completed_at')) {
                $table->timestamp('questionnaire_completed_at')->nullable()->index()->after('role');
            }

            if ($missingColumns->contains('access_unlocked_at')) {
                $table->timestamp('access_unlocked_at')->nullable()->index()->after('questionnaire_completed_at');
            }

            if ($missingColumns->contains('resume_uploaded_at')) {
                $table->timestamp('resume_uploaded_at')->nullable()->after('access_unlocked_at');
            }

            if ($missingColumns->contains('resume_analyzed_at')) {
                $table->timestamp('resume_analyzed_at')->nullable()->index()->after('resume_uploaded_at');
            }

            if ($missingColumns->contains('profile_completed_at')) {
                $table->timestamp('profile_completed_at')->nullable()->index()->after('resume_analyzed_at');
            }

            if ($missingColumns->contains('last_login_at')) {
                $table->timestamp('last_login_at')->nullable()->after('profile_completed_at');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Intentionally no-op. This migration only patches older local databases.
    }
};
