<?php

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

class Echomails extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
		Schema::create('echomails', function (Blueprint $table) {
			$table->id();
			$table->timestamps();
			$table->softDeletes();
			$table->string('mid')->nullable();

			$table->string('to',128);
			$table->string('from',128);
			$table->string('subject',256);
			$table->dateTimeTz('datetime');
			$table->tinyInteger('tzoffset');

			$table->string('msgid')->nullable();
			$table->string('replyid')->nullable();

			$table->text('msg');
			$table->text('msg_src')->nullable();
			$table->string('msg_crc')->nullable();
			$table->string('tagline')->nullable();
			$table->string('tearline')->nullable();
			$table->string('origin')->nullable();

			$table->tinyInteger('flags')->nullable();
			$table->jsonb('rogue_path')->nullable();
			$table->jsonb('rogue_seenby')->nullable();
			$table->jsonb('kludges')->nullable();

			$table->bigInteger('echoarea_id');
			$table->foreign('echoarea_id')->references('id')->on('echoareas');

			$table->bigInteger('fftn_id');
			$table->foreign('fftn_id')->references('id')->on('addresses');
		});

		Schema::create('echomail_seenby', function (Blueprint $table) {
			$table->bigInteger('address_id');
			$table->foreign('address_id')->references('id')->on('addresses');

			$table->bigInteger('echomail_id');
			$table->foreign('echomail_id')->references('id')->on('echomails');

			$table->string('mid')->nullable();
			$table->datetime('export_at')->nullable();
			$table->datetime('sent_at')->nullable();
			$table->string('packet')->nullable();

			$table->unique(['address_id','echomail_id']);
		});

		Schema::create('echomail_path', function (Blueprint $table) {
			$table->id();

			$table->bigInteger('address_id');
			$table->foreign('address_id')->references('id')->on('addresses');

			$table->unique(['id','echomail_id']);
			$table->unique(['echomail_id','address_id','parent_id']);

			$table->bigInteger('parent_id')->nullable();
			$table->foreign(['parent_id','echomail_id'])->references(['id','echomail_id'])->on('echomail_path');

			$table->bigInteger('echomail_id');
			$table->foreign('echomail_id')->references('id')->on('echomails');
		});
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
		Schema::dropIfExists('echomail_seenby');
		Schema::dropIfExists('echomail_path');
		Schema::dropIfExists('echomails');
    }
}