<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::dropIfExists('oauth_access_tokens');
		Schema::dropIfExists('oauth_auth_codes');
		Schema::dropIfExists('oauth_clients');
		Schema::dropIfExists('oauth_personal_access_clients');
		Schema::dropIfExists('oauth_refresh_tokens');
		Schema::dropIfExists('external_integrations');
		Schema::dropIfExists('external_account');

		DB::statement('RENAME TABLE ab_oauth TO provider_oauth');
		DB::statement('ALTER TABLE provider_oauth MODIFY active tinyint(1) NOT NULL');
		DB::statement('ALTER TABLE provider_oauth MODIFY app_id VARCHAR(256) NOT NULL,MODIFY secret VARCHAR(256) DEFAULT NULL');

		Schema::table('provider_oauth', function (Blueprint $table) {
			$table->dropForeign('ab_oauth_site_id_foreign');
			$table->dropIndex('ab_oauth_id_site_id_index');
			$table->dropIndex('ab_oauth_site_id_foreign');

			$table->foreign(['site_id'])->references(['id'])->on('sites');
		});

		DB::statement('RENAME TABLE quickbooks_tokens TO provider_tokens');
		DB::statement('ALTER TABLE provider_tokens MODIFY realm_id TEXT DEFAULT NULL,MODIFY access_token TEXT NOT NULL,MODIFY refresh_token TEXT DEFAULT NULL');
		DB::statement('ALTER TABLE provider_tokens MODIFY access_token_expires_at datetime DEFAULT NULL,MODIFY refresh_token_expires_at datetime DEFAULT NULL');

		Schema::table('provider_tokens', function (Blueprint $table) {
			$table->integer('provider_oauth_id')->unsigned();
			$table->integer('site_id')->unsigned();

			$table->unique(['provider_oauth_id','user_id']);
			$table->foreign(['user_id','site_id'])->references(['id','site_id'])->on('users');
			$table->foreign(['provider_oauth_id','site_id'])->references(['id','site_id'])->on('provider_oauth');
		});

		// delete from ab_account_oauth where account_id=144;
		// update ab_account_oauth set user_id =1 where account_id=1;
		// update ab_account_oauth set user_id =109 where id=12;
		DB::statement('RENAME TABLE ab_account_oauth TO user_oauth');
		DB::statement('ALTER TABLE user_oauth RENAME COLUMN oauth_id TO provider_oauth_id');
		Schema::table('user_oauth', function (Blueprint $table) {
			$table->datetime('created_at')->nullable()->after('id');
			$table->datetime('updated_at')->nullable()->after('created_at');
		});

		foreach (\App\Models\UserOauth::withoutGlobalScope(\App\Models\Scopes\SiteScope::class)->cursor() as $o) {
			if ($o->date_orig)
				$o->created_at = \Carbon\Carbon::createFromTimestamp($o->date_orig);
			if ($o->date_last)
				$o->updated_at = \Carbon\Carbon::createFromTimestamp($o->date_last);

			if ($o->getRawOriginal('oauth_data') && ! is_array($o->oauth_data)) {
				try {
					$o->oauth_data = unserialize(gzuncompress($o->getRawOriginal('oauth_data')));
				} catch (Exception $e) {
				}
			}

			$o->save();
		}

		DB::statement('ALTER TABLE user_oauth MODIFY provider_oauth_id int unsigned NOT NULL');
		Schema::table('user_oauth', function (Blueprint $table) {
			$table->dropColumn(['date_orig','date_last','account_id']);
			$table->dropForeign('ab_account_oauth_site_id_foreign');
			$table->dropIndex('ab_account_oauth_site_id_foreign');
			$table->dropIndex('ab_account_oauth_id_site_id_index');
			$table->foreign(['user_id','site_id'])->references(['id','site_id'])->on('users');
			$table->foreign(['provider_oauth_id','site_id'])->references(['id','site_id'])->on('provider_oauth');
		});

		// Fix incorrect site references
		Schema::table('accounts', function (Blueprint $table) {
			$table->dropForeign(['site_id']);
		});
		Schema::table('services', function (Blueprint $table) {
			$table->dropForeign(['site_id']);
		});
		Schema::table('costs', function (Blueprint $table) {
			$table->dropForeign(['site_id']);
			$table->foreign(['site_id'])->references(['id'])->on('sites');
		});
		Schema::table('products', function (Blueprint $table) {
			$table->dropForeign(['site_id']);
			$table->foreign(['site_id'])->references(['id'])->on('sites');
		});
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        abort(500,'cant go back');
    }
};