import { AccountingAddService } from '../services/accountingAddService.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 accountingAdd {

    constructor() {
        this.generalService = new GeneralService();
        this.accountingAddService = new AccountingAddService();
        this.Interface = new Interface();
    }

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

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

            let actnum = req.body.request.actnum;
            database = decoded.organization;

            aryResult = await this.accountingAddService.getAccountingAdd(database, actnum);
            latSeq = await this.accountingAddService.getLatestAccountingSeq(database);
        } 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, latSeq[0].actseq);
                return prommis
            } else {
                return sendError('คีย์หลักซ้ำในระบบ', 'Duplicate Primary Key');
            }
        }
    }


    async makeArySave(req, seq) {
        let arysave = {
            methods: 'post',
            actseq: seq + 1,
            actnum: req.body.request.actnum,
            actacpdtm: req.body.request.actacpdtm,
            actcat: req.body.request.actcat,
            actqty: req.body.request.actqty,
            actcmt: req.body.request.actcmt,
            acttyp: req.body.request.acttyp
        }
        return this.Interface.saveInterface('actmst', arysave, req);
    }
}
