<?php

use Phalcon\Db\Column;
use Phalcon\Db\Index;
use Phalcon\Db\Reference;
use Phalcon\Mvc\Model\Migration;

/**
 * Class RolesMigration_211
 */
class UsersRolesMigration_124 extends Migration
{
    /**
     * Define the table structure
     *
     * @return void
     */
    public function morph()
    {
        $this->morphTable('users_roles', [
            'columns' => [
                new Column(
                    'id',
                    [
                        'type' => Column::TYPE_INTEGER,
                        'notNull' => true,
                        'autoIncrement' => true,
                        'primary' => true
                    ]
                ),
                new Column(
                    'user_id',
                    [
                        'type' => Column::TYPE_INTEGER,
                        'notNull' => true
                    ]
                ),
                new Column(
                    'role_id',
                    [
                        'type' => Column::TYPE_INTEGER,
                        'notNull' => true
                    ]
                ),
                new Column(
                    'created_at',
                    [
                        'type' => Column::TYPE_TIMESTAMP,
                    ]
                ),
                new Column(
                    'updated_at',
                    [
                        'type' => Column::TYPE_TIMESTAMP,
                    ]
                ),
                new Column(
                    'deleted_at',
                    [
                        'type' => Column::TYPE_TIMESTAMP,
                    ]
                )
            ],
            'indexes' => [
                new Index(
                    'users_roles_unique',
                    [
                        'user_id',
                        'role_id'
                    ],
                    'UNIQUE'
                )
            ]
        ]);
    }

    /**
     * Run the migrations
     *
     * @return void
     */
    public function up()
    {
    }

    /**
     * Reverse the migrations
     *
     * @return void
     */
    public function down()
    {
        self::$connection->execute('DROP TABLE users_roles');
    }


    /**
     * This method is called after the table was created
     *
     * @return void
     */
    public function afterCreateTable()
    {
        self::$connection->execute("
            insert into jaga.users_roles(user_id, role_id)
            select um_user_id, '1' from public.um_user_role
            group by um_user_id
        ");
    }
}
