DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `account`.`account_enable`(vSelf INT)
BEGIN
/**
 * Enables a worker's account and sets up email configurations.
 */
    UPDATE user
        SET active = TRUE
        WHERE id = vSelf;

    INSERT IGNORE INTO account
        SET id = vSelf;

    INSERT IGNORE INTO mailAliasAccount (mailAlias, account)
        SELECT  id, vSelf
            FROM mailAlias
            WHERE alias = 'general';

    INSERT IGNORE INTO mailForward (account, forwardTo)
        SELECT vSelf, email
            FROM user
            WHERE id = vSelf;
END$$
DELIMITER ;

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_updateBusiness`(vSelf INT)
BEGIN
/**
 * Activates an account and configures its email settings.
 *
 * @param vSelf account id.
 */
    DECLARE vOldBusinessFk INT;
    DECLARE vNewBusinessFk INT;

    SELECT businessFk INTO vOldBusinessFk FROM worker WHERE id = vSelf;

    SELECT id INTO vNewBusinessFk 
        FROM business 
        WHERE workerFk = vSelf
            AND util.VN_CURDATE() BETWEEN started AND IFNULL(ended, util.VN_CURDATE());

    UPDATE worker
        SET businessFk = vNewBusinessFk
        WHERE id = vSelf;

    IF NOT (vOldBusinessFk <=> vNewBusinessFk) THEN
        IF vNewBusinessFk IS NULL THEN 
            CALL workerDisable(vSelf);
        END IF;
        IF vOldBusinessFk IS NULL THEN 
            CALL account.account_enable(vSelf);
        END IF;
    END IF;
END$$
DELIMITER ;
