<?php

declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

final class CreateBrokerData extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change(): void
    {
        $this->execute('SET unique_checks=0; SET foreign_key_checks=0;');
        $this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
        $this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");

        $this->table('broker_data')
            ->addColumn('broker_rut', 'integer', ['signed' => false, 'null' => false])
            ->addColumn('representative_id', 'integer', ['signed' => false, 'null' => true, 'default' => null])
            ->addColumn('legal_name', 'string', ['length' => 255, 'default' => null, 'null' => true])
            ->addForeignKey('broker_rut', 'brokers', ['rut'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->addForeignKey('representative_id', 'broker_contacts', ['id'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->create();

        $this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
    }
}
