<?php

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

class CreateAccountsTable extends Migration
{
    public function up()
    {
        Schema::create('accounts', function(Blueprint $table)
        {
            $table->increments('id')->unsigned();
            $table->integer('organization_id')->unsigned()->nullable();
            $table->integer('status_id')->unsigned();
            $table->integer('policy_id')->unsigned()->nullable();
            $table->boolean('is_manager')->default('0');

            // Username is indexed, it's a sha256 of the username_readable
            $table->binary('username', 32)->unique();
            $table->binary('password', 60);
            $table->string('username_readable', 255);
            $table->string('first_name', 255);
            $table->string('last_name', 255);
            $table->string('email', 255);

            // Additional attributes
            $table->json('additional');

            // Used for password history. History column stores old user passwords.
            $table->json('history');

            // Stores authentication attempts (array of datetimes). If password policy is in effect, this column
            // is used to determine when and how to lock the account out after X unsuccessful logins
            $table->json('attempts');

            // Messages about account status change etc.
            $table->json('messages');

            // Timestamps
            $table->timestamps();

            // When the last succesful login was made
            $table->timestamp('last_login_at');

            // Last password change
            $table->timestamp('password_changed_at');

            // When the account was locked at. Used for automatic account un-lock
            $table->timestamp('locked_at');

            // When the account was unlocked
            $table->timestamp('unlocked_at');
        });
    }

    public function down()
    {
        Schema::disableForeignKeyConstraints();
        Schema::dropIfExists('accounts');
    }
}