import { ProjectSearchService } from '../services/projectSearchService.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 projectSearch {

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

  async onNavigate(req, res) {
    this.generalService.devhint(1, 'projectSearch.js', 'onNavigate() start');
    let organization = req.body.organization || 'dbo'; // Default Schema
    const prommis = await this.onProjectSearch(req, res, organization);
    return prommis;
  }

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

      // ใช้ Organization จาก Token ถ้ามี
      database = decoded.organization || database 
      
      let columnParams = req.query.column
      
  
      if (columnParams == 'edit') {
        let column = `prjnam, prjwntbdg, ${database}.translatedtl('COMSTT', prjcomstt) as prjcomstt`
        condition['prjseq'] = req.body.request.prjseq
        
        // เรียก Service ตัวเดิม (Simple)
        aryResult = await this.projectSearchService.getProjectSearch(database, column, condition);

      } if (columnParams == 'result' || columnParams == undefined || columnParams == '') {
        
        // กำหนดเงื่อนไข (ถ้ามีส่งมา)
        condition['prjseq'] = req.body.request.prjseq;
        
        //  สร้าง Column String ที่มี Subquery ดึงงบจาก trnmst
        let column = `
          prjseq, 
          prjnam, 
          usrthinam as prjusrnam, 
          prjwntbdg,   
          
          ${database}.translatebdg(
            (
              SELECT string_agg(DISTINCT trnbdgcod, ',') 
              FROM ${database}.trnmst 
              WHERE trnprjseq = prjseq
            )
          ) as prjbdgnam,
          (
            SELECT string_agg(DISTINCT trnbdgcod, ',') 
            FROM ${database}.trnmst 
            WHERE trnprjseq = prjseq
          ) as prjbdgcod,
          
          prjacpbdg, 
          ${database}.translatedtl('COMSTT', prjcomstt) as prjcomsttnam,
          prjcomstt,
          prjacpdtm
        `;

        // ใช้ Service ตัวใหม่ (Detail Search / Join)
        aryResult = await this.projectSearchService.getProjectDetailSearch(database, column, condition);
      }

    } catch (error) {
      console.error(error);
      idx = 1;
    } finally { 
      if (idx === 1) return sendError('เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error');
      if (!aryResult || aryResult.length === 0) return sendError('ไม่พบการมีอยู่ของข้อมูล', 'Cannot Find Any Data');
      return aryResult
    }
  }
}
