-- LoanProduct
ALTER TABLE `LoanProduct` 
CHANGE COLUMN `interest_rate` `min_interest_rate` DECIMAL(13,10) NOT NULL  , 
CHANGE COLUMN `effective_interest_rate` `min_effective_interest_rate` DECIMAL(13,10) DEFAULT NULL  ,
ADD COLUMN `max_interest_rate` DECIMAL(13,10) NOT NULL  AFTER `min_effective_interest_rate` , 
ADD COLUMN `max_effective_interest_rate` DECIMAL(13,10) DEFAULT NULL  AFTER `max_interest_rate` ;

UPDATE LoanProduct SET max_interest_rate = min_interest_rate, max_effective_interest_rate = min_effective_interest_rate;

-- LoanAccount
ALTER TABLE `LoanAccount` 
ADD COLUMN `interest_rate` DECIMAL(13,10) NOT NULL  AFTER `loan_purpose_id` ;

-- LoanScheduleAmountRef

ALTER TABLE `LoanScheduleAmountRef` 
ADD COLUMN `interest_rate` DECIMAL(13,10) NOT NULL  AFTER `product_id`;

CREATE UNIQUE INDEX loanscheduleamountref_proj_num_idx ON LoanScheduleAmountRef(product_id, interest_rate, loan_amount, installment_amount, proj_num_installments, first_repay_moratorium_days, disbursement_date);
CREATE UNIQUE INDEX loanscheduleamountref_num_idx ON LoanScheduleAmountRef(product_id, interest_rate, loan_amount, installment_amount, num_installments, first_repay_moratorium_days, disbursement_date);

ALTER TABLE `LoanScheduleAmountRef` 
DROP INDEX `loanscheduleamountref_prod_amt_num2_idx` , 
DROP INDEX `loanscheduleamountref_prod_amt_num1_idx` ;

-- Run this command to get the intrates and build the query
select id, min_interest_rate into outfile '/tmp/lp.txt' from LoanProduct;
-- awk '{printf "UPDATE LoanAccount SET interest_rate = %s WHERE product_id = %s;\n", $2, $1}' /tmp/lp.txt
-- awk '{printf "UPDATE LoanScheduleAmountRef SET interest_rate = %s WHERE product_id = %s;\n", $2, $1}' /tmp/lp.txt
