<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    
    <query name="findAllLoanTypeByOffice">
        <![CDATA[
            SELECT 
                lt.id as id,
                lt.payment as payment
            FROM 
                LoanType lt 
            WHERE 
                lt.office = :office AND
                lt.convenio = 'DISABLED'                
            ORDER BY lt.payment
        ]]>
    </query>
    
    <query name="findAllLoanTypeWithDescrpitionByOffice">
        <![CDATA[
            SELECT 
                lt.id as id,
                lt.payment as payment,
                lt.loanTypeName as loanTypeName
            FROM 
                LoanType lt 
            WHERE 
                lt.office = :office AND
                lt.convenio = 'DISABLED'                
            ORDER BY lt.payment
        ]]>
    </query> 
    
    <query name="findNewCreditLineByLoanId">
        <![CDATA[
            SELECT 
                lt.id as id,
                lt.payment as payment
            FROM LoanType lt
            WHERE lt.office = :office AND
                lt.payment <= (
                    CASE
                        WHEN (SELECT COUNT(lfn.id) AS total 
                                FROM LoanFeeNotification lfn 
                                WHERE lfn.loan = :loan) BETWEEN 0 AND 1
                        THEN (SELECT lt.payment + 1000 
                                FROM Loan l
                                INNER JOIN LoanType lt ON l.loanType = lt.id 
                                WHERE l.id = :loanId) 
                        WHEN (SELECT COUNT(lfn.id) AS total 
                                FROM LoanFeeNotification lfn 
                                WHERE lfn.loan = :loan) BETWEEN 2 AND 3
                        THEN (SELECT lt.payment 
                                FROM Loan l
                                INNER JOIN LoanType lt ON l.loanType = lt.id 
                                WHERE l.id = :loanId) 
                        WHEN (SELECT COUNT(lfn.id) AS total 
                                FROM LoanFeeNotification lfn 
                                WHERE lfn.loan = :loan) BETWEEN 4 AND 5
                        THEN (SELECT lt.payment - 1000 
                                FROM Loan l
                                INNER JOIN LoanType lt ON l.loanType = lt.id 
                                WHERE l.id = :loanId) 
                        ELSE
                            0
                    END
                    )
            ORDER BY lt.payment DESC
        ]]>
    </query>
    
    <query name="findAllDataLoanTypeByOffice">
        <![CDATA[
            SELECT 
                lt
            FROM LoanType lt 
                WHERE office = :office
            ORDER BY lt.loanTypeName
        ]]>
    </query>
    
</hibernate-mapping>
