<?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
    {
		Schema::create('mailers',function (Blueprint $table) {
			$table->id();
			$table->string('name')->unqiue();
			$table->integer('priority')->unsigned()->unique();
		});

		Schema::create('mailer_system',function (Blueprint $table) {
			$table->integer('port')->unsigned();
			$table->dateTime('last_poll')->nullable();
			$table->boolean('active');
			$table->integer('attempts')->unsigned()->nullable();

			$table->bigInteger('system_id');
			$table->foreign('system_id')->references('id')->on('systems');
			$table->bigInteger('mailer_id');
			$table->foreign('mailer_id')->references('id')->on('mailers');

			$table->unique(['system_id','mailer_id']);
			$table->unique(['system_id','port']);
		});

		Schema::table('systems',function (Blueprint $table) {
			$table->dropUnique(['mailer_type','mailer_address','mailer_port']);
		});

		$binkp = new \App\Models\Mailer;
		$binkp->name = 'BINKP';
		$binkp->priority = 1;
		$binkp->save();

		$emsi = new \App\Models\Mailer;
		$emsi->name = 'EMSI';
		$emsi->priority = 2;
		$emsi->save();

		foreach (\App\Models\System::whereNotNull('mailer_address')->cursor() as $o) {
			if ($o->mailer_type & \App\Models\Setup::O_BINKP)
				$type = $binkp;
			elseif ($o->mailer_type & \App\Models\Setup::O_EMSI)
				$type = $emsi;
			else
				$type = NULL;

			if (! $type)
				abort(500,sprintf('No mailer type [%d] :',$o->mailer_type));

			$o->mailers()->sync([$type->id=>[
				'port'=>$o->mailer_port,
				'active'=>TRUE,
			]]);

			$o->address = $o->mailer_address;
			$o->mailer_port = null;
			$o->mailer_type = null;
			$o->mailer_address = null;
			$o->save();
		}

		Schema::table('systems',function (Blueprint $table) {
			$table->dropColumn(['mailer_type','mailer_address','mailer_port']);
		});
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
		abort(500,'Cant go back');
        Schema::dropIfExists('mailer_system');
		Schema::dropIfExists('mailers');
		Schema::table('systems',function (Blueprint $table) {
			$table->unique(['mailer_type','mailer_address','mailer_port']);
		});
    }
};