/*
Copyright (C) 2024 Centro de Computacao Cientifica e Software Livre
Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR

This file is part of simcaq-node.

simcaq-node is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

simcaq-node is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
*/

const express = require('express');

const studentCostApp = express.Router();

const libs = `${process.cwd()}/libs`;

const squel = require('squel');

const query = require(`${libs}/middlewares/query`).query;

const response = require(`${libs}/middlewares/response`);

const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);

const aggregateData = require(`${libs}/middlewares/aggregateData`);

const id2str = require(`${libs}/middlewares/id2str`);

const config = require(`${libs}/config`); 

const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;

let rqf = new ReqQueryFields();

studentCostApp.use(cache('15 day'));

studentCostApp.get('/years', (req, res, next) => {
    req.sql.from('despesas')
    .field('DISTINCT despesas.ano_censo', 'year')
    .where('despesas.ano_censo is not null')
    next();
}, query, response('years'));

rqf.addField({
    name: 'filter',
    field: false,
    where: true
}).addField({
    name: 'dims',
    field: true,
    where: false
}).addValue({
    name: 'min_year',
    table: 'despesas',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '>=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'max_year',
    table: 'despesas',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '<=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'region',
    table: 'estado',
    tableField: ['nome_ente', 'cod_ibge', 'id', 'regiao_id'],
    resultField: ['state_name', 'state_cod_ibge', 'state_id', 'region_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'regiao_id',
    },
    join: {
        primary: 'id',
        foreign: 'cod_ibge',
        foreignTable: 'despesas'
    }
})

studentCostApp.get('/', rqf.parse(), rqf.build(),  (req, res, next) => {
    if (req.query.dims && req.query.dims.includes('despesas')) {
        let whereCondition = req.query.filter.includes("region") ? "" : "despesas.cod_ibge = 0";
        let filterId;
        const filters = req.query.filter.split(",");
        filters.forEach((filter) => {
            if (filter.includes("state") || filter.includes("city")) {
                filterId = Number(filter.split(":")[1].replace(/"/g, ""));
                whereCondition = `despesas.cod_ibge = ${filterId}`
            }
        })

        req.sql.from('despesas')
        .field('despesas.ano_censo', 'year')
        .field('despesas.ano_censo', 'total_ano')
        .field('despesas.nome_ente', 'total_nome_ente')
        .field('despesas.despesas', 'total_despesas')
        .field('matriculas_publica', 'total_matriculas_publica')
        .field('matriculas_publicas_mais_conveniada', 'total_matriculas_publicas_mais_conveniada')
        .field('gasto_aluno_ano_publica', 'total_gasto_aluno_ano_publica')
        .field('gasto_aluno_mes_publica', 'total_gasto_aluno_mes_publica')
        .field('gasto_aluno_ano_publica_mais_conveniada', 'total_gasto_aluno_ano_publica_mais_conveniada')
        .field('gasto_aluno_mes_publica_mais_conveniada', 'total_gasto_aluno_mes_publica_mais_conveniada')
        .where(`${whereCondition}`)
        .order('despesas.cod_ibge')
        .order('despesas.ano_censo')
    }

    next();
}, query, aggregateData, id2str.transform(false), response('student_cost'));

module.exports = studentCostApp;