from alembic import op


revision = "0004"
down_revision = "0003"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute(
        """
        CREATE OR REPLACE FUNCTION v3.del_vsp(p_vsp_id integer, p_deleted_by integer)
         RETURNS integer
         LANGUAGE plpgsql
        AS $function$
        DECLARE
            v_old RECORD;
            v_usr RECORD;
        BEGIN
            SELECT vsp.id, vsp.branch_id
              INTO v_old
              FROM v3.vsp vsp WHERE vsp.id = p_vsp_id;
            IF NOT FOUND THEN
                RAISE EXCEPTION 'vsp #% не существует', p_vsp_id;
            END IF;
            SELECT usr.id
              INTO v_usr
              FROM v3.app_user usr WHERE usr.id = p_deleted_by;
            IF NOT FOUND THEN
                RAISE EXCEPTION 'user #% не существует', p_deleted_by;
            END IF;

            UPDATE v3.vsp
               SET is_deleted = true,
                   is_active = false,
                   updated_by = p_deleted_by
             WHERE id = p_vsp_id;
            UPDATE v3.vsp
               SET closed_at = CURRENT_DATE
             WHERE id = p_vsp_id
               AND closed_at IS NULL;

            PERFORM v3.log_event(
                'DELETE_VSP', 'VSP',
                jsonb_build_object(
                    'vsp_id', p_vsp_id,
                    'entity_id', p_vsp_id,
                    'branch_id', v_old.branch_id,
                    'updated_by', p_deleted_by
                ),
                null, null, v_old.branch_id
            );

            RETURN p_vsp_id;
        END;
        $function$;
        """
    )


def downgrade() -> None:
    pass
