<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

final class Task2012181648 extends AbstractMigration
{
    public function up(): void
    {
        $this->migrarIdComercial();
        $this->upAlterarCampo();
        $this->upCampoPrepostos();
        $this->upNovaTabela();
        $this->upRenomearAcao();
    }

    public function down(): void
    {
        $this->downCampoPrepostos();
        $this->downNovaTabela();
        $this->downRenomearAcao();
    }

    private function migrarIdComercial()
    {
        $this->execute(<<<SQL
update sistema.prepostos set id_comercial = corretores.id_comercial from sistema.corretores where corretores.id = prepostos.id_corretor and corretores.id_comercial <> prepostos.id_comercial;
SQL
);
    }

    private function upAlterarCampo()
    {
        $this->execute(<<<SQL
ALTER TABLE sistema.prepostos ALTER COLUMN ds_nome_responsavel DROP NOT NULL;
ALTER TABLE sistema.prepostos ALTER COLUMN ds_email DROP NOT NULL;
SQL
        );
    }

    private function upCampoPrepostos()
    {
        $this->execute(<<<SQL
alter table sistema.prepostos add column if not exists fl_permite_alterar_comissao boolean default false;
SQL
        );
    }

    private function upNovaTabela()
    {
        $this->execute(<<<SQL
create table sistema.prepostos_periodo_cadastro_anual (
  id SERIAL,
  id_preposto int not null,
  dt_inicio date,
  dt_fim date,
  fl_cadastro_validado boolean default false,
  CONSTRAINT pk_prepostos_periodo_cadastro_anual PRIMARY KEY(id),
  CONSTRAINT fk_prepostos FOREIGN KEY(id_preposto) REFERENCES sistema.prepostos(id)
) INHERITS (public.campos_default);
SQL
        );
    }

    private function upRenomearAcao()
    {
        $this->execute(<<<SQL
update sistema.acao set ds_label = 'Sublogins' where ds_label = 'Prepostos' and id_parent = 4;
SQL
        );
    }

    private function downCampoPrepostos()
    {
        $this->execute(<<<SQL
alter table sistema.prepostos drop column if exists fl_permite_alterar_comissao;
SQL
        );
    }

    private function downNovaTabela()
    {
        $this->execute(<<<SQL
drop table sistema.prepostos_periodo_cadastro_anual;
SQL
        );
    }

    private function downRenomearAcao()
    {
        $this->execute(<<<SQL
update sistema.acao set ds_label = 'Prepostos' where ds_label = 'Sublogins' and id_parent = 4;
SQL
        );
    }
}
