import { BudgetSetupService } from '../services/budgetSetupService.js'
import { sendError } from '../utils/response.js'
// import { OftenError } from '../utils/oftenError.js'
import { GeneralService } from '../share/generalservice.js';
import { trim_all_array } from '../utils/trim.js'
import { verifyToken, generateToken } from '../utils/token.js'

export class budgetSetup {

  constructor() {
    this.generalService = new GeneralService();
    this.BudgetSetupService = new BudgetSetupService();
  }

  async onNavigate(req, res) {
    this.generalService.devhint(1, 'budgetSetup.js', 'onNavigate() start');
    let organization = req.body.organization;
    const prommis = await this.onBudgetSetup(req, res, organization);
    return prommis;
  }

  async onBudgetSetup(req, res, database) {
    let idx = -1
    let result = []
    try {
      // let username = req.body.request.username;
      // let password = req.body.request.password;
      let token = req.body.request.token;
      const decoded = verifyToken(token);

      database = decoded.organization


      result = await this.BudgetSetupService.getBudgetSetup(database); // เช็คกับ db กลาง ส่ง jwttoken ออกมา
    //   this.generalService.devhint(1, 'budgetSetup.js', 'Login success');
    } catch (error) {
      idx = 1;
    } finally { 
      if (idx === 1) return sendError('เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error');
      if (!result) return sendError('ไม่พบข้อมูล', 'Data not found');
      // แยกกลุ่ม income / expense
      let income = result.filter(item => item.dtltblcod === 'ACTCAT_INC').map(({ dtltblcod, ...rest }) => rest);

      let expense = result.filter(item => item.dtltblcod === 'ACTCAT_EXP').map(({ dtltblcod, ...rest }) => rest);

      let arydiy = { 
        income ,
        expense 
      };

    return arydiy
    }
  }
}
