<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (DB::getDriverName() === 'mysql') {
            DB::statement("ALTER TABLE users MODIFY role ENUM('admin', 'support_team', 'mentor', 'student', 'user') NOT NULL DEFAULT 'user'");
        }

        Schema::create('mentor_students', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('mentor_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('student_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('student_email')->nullable();
            $table->string('invite_code')->unique();
            $table->string('status')->default('invited');
            $table->timestamp('joined_at')->nullable();
            $table->timestamps();

            $table->unique(['mentor_id', 'student_id']);
        });

        Schema::create('trade_comments', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('trade_id')->constrained()->cascadeOnDelete();
            $table->foreignId('mentor_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('student_id')->constrained('users')->cascadeOnDelete();
            $table->text('comment');
            $table->timestamps();
        });

        Schema::table('trades', function (Blueprint $table): void {
            $table->string('review_status')->default('private')->after('screenshot_path');
            $table->timestamp('submitted_for_review_at')->nullable()->after('review_status');
        });
    }

    public function down(): void
    {
        if (DB::getDriverName() === 'mysql') {
            DB::table('users')
                ->whereIn('role', ['mentor', 'student'])
                ->update(['role' => 'user']);
        }

        Schema::table('trades', function (Blueprint $table): void {
            $table->dropColumn(['review_status', 'submitted_for_review_at']);
        });

        Schema::dropIfExists('trade_comments');
        Schema::dropIfExists('mentor_students');

        if (DB::getDriverName() === 'mysql') {
            DB::statement("ALTER TABLE users MODIFY role ENUM('admin', 'support_team', 'user') NOT NULL DEFAULT 'user'");
        }
    }
};
