<?php

use App\Models\User;
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
    {
        // Remove tables from larascord
        Schema::dropIfExists('discord_access_tokens');
        Schema::dropIfExists('personal_access_tokens');

        // Drop columns from larascord
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('discriminator');
            $table->dropColumn('remember_token');
            $table->dropColumn('banner');
            $table->dropColumn('banner_color');
            $table->dropColumn('accent_color');
            $table->dropColumn('premium_type');
            $table->dropColumn('public_flags');
            $table->dropColumn('verified');
            $table->dropColumn('mfa_enabled');
            $table->dropColumn('global_name');
            $table->dropColumn('locale');
        });

        // Change & Add Columns
        Schema::table('users', function (Blueprint $table) {
            // Rename
            $table->renameColumn('username', 'name');
            $table->renameColumn('avatar', 'discord_avatar');
            $table->string('avatar')->nullable()->after('email');

            // Re-Add Email verification
            $table->timestamp('email_verified_at')->nullable()->after('email');

            // Re-Add Password Auth
            $table->string('password')->nullable()->after('email_verified_at');
            $table->rememberToken()->after('password');
        });

        /**
         * --------------------------------------------------------------------
         * Fix Discord Profile Pictures
         * --------------------------------------------------------------------
         * The oauth package by socialite now returns a full url of the avatar.
         * Meaning all the old entries have to be fixed.
         */
        foreach (User::whereNotNull('discord_avatar')->get() as $user) {
            $isGif = preg_match('/a_.+/m', $user->discord_avatar) === 1;
            $extension = $isGif ? 'gif' : 'webp';
            $user->discord_avatar = sprintf('https://cdn.discordapp.com/avatars/%s/%s.%s', $user->id, $user->discord_avatar, $extension);
            $user->save();
        }
    }
};
