import { BudgetAddService } from '../services/budgetAddService.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'
import { Interface } from '../interfaces/Interface.js';


export class budgetAdd {

  constructor() {
    this.generalService = new GeneralService();
    this.Interface = new Interface();
    this.budgetAddService = new BudgetAddService();
  }

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

  async onBudgetAdd(req, res, database) {
    let idx = -1
    let aryResult = []
    try {
      let token = req.headers.authorization?.split(' ')[1];
      const decoded = verifyToken(token);

      let name = req.body.request.bdgnam;
      let id = req.body.request.bdgseq;
      database = decoded.organization

       aryResult = await this.budgetAddService.getBudgetAdd(database, name); // เช็คกับ db กลาง ส่ง jwttoken ออกมา
    //   this.generalService.devhint(1, 'budgetSearch.js', 'Login success');
    } catch (error) {
      idx = 1;
    } finally { 
    if (idx === 1) return sendError('เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error');
    // if (!aryResult) return sendError('ไม่พบการมีอยู่ของข้อมูล', 'Cannot Find Any Data');

    if (aryResult == 0){
      let prommis = await this.makeArySave(req);
      return prommis
    } else {
      return sendError('คีย์หลักซ้ำในระบบ', 'Duplicate Primary Key');
    }
    }
  }


  async makeArySave(req){
    let arysave = {
      methods: 'post',
      bdgseq: req.body.request.bdgseq,
      bdgnam: req.body.request.bdgnam,
      bdgcod: req.body.request.bdgcod,
      bdgttl: req.body.request.bdgttl
    }
   return this.Interface.saveInterface('bdgmst', arysave, req); 
  }
}
