import type { PoolClient } from "pg";

// 대상 모듈별 상태 업데이트 (approval.xml의 XxxApprovalStatus 쿼리 대응)
// ApprovalService.completeRouteInfo / rejectRouteInfo 로직 포팅
export async function updateTargetStatus(
  client: PoolClient,
  targetType: string,
  targetObjId: string,
  status: string,
  userId: string
): Promise<void> {
  switch (targetType) {
    case "PURCHASE_ORDER":
      // purchaseOrderApprovalStatus — MULTI_MASTER_OBJID도 처리 (동시발주)
      await client.query(
        `UPDATE purchase_order_master
         SET status = $1
           ${status === "approvalComplete" ? ", purchase_date = TO_CHAR(now(), 'YYYY-MM-DD')" : ""}
         WHERE (objid::text = $2::text OR multi_master_objid::text = $2::text)
           AND status != 'cancel'`,
        [status, targetObjId]
      );
      break;
    case "AS_MNG":
      await client.query(
        `UPDATE as_mng SET status_cd = $1 WHERE objid = $2::numeric`,
        [status, targetObjId]
      );
      break;
    case "CSM":
      await client.query(
        `UPDATE customer_service_mgmt SET status = $1 WHERE objid = $2`,
        [status, targetObjId]
      ).catch(() => { /* 테이블 없을 수 있음 */ });
      break;
    case "EXPENSE_APPLY":
      await client.query(
        `UPDATE expense_master SET status = $1 WHERE expense_master_objid = $2::numeric`,
        [status, targetObjId]
      );
      break;
    case "MATERIAL_APPLY":
      await client.query(
        `UPDATE material_master_mgmt SET status_cd = $1 WHERE material_master_objid = $2::numeric`,
        [status, targetObjId]
      ).catch(() => { /* */ });
      break;
    case "EO_MNG":
      if (status === "approvalComplete") {
        await client.query(
          `UPDATE eo_mng SET status = $1, deploy_date = now(), deploy_writer = $2
           WHERE objid = $3::numeric`, [status, userId, targetObjId]
        ).catch(() => {});
      } else {
        await client.query(
          `UPDATE eo_mng SET status = $1 WHERE objid = $2::numeric`, [status, targetObjId]
        ).catch(() => {});
      }
      break;
    case "ISSUE_RELEASE":
      await client.query(
        `UPDATE issue_mgmt SET wpst_cd = $1, ret_date = now() WHERE objid = $2`,
        [status, targetObjId]
      ).catch(() => {});
      break;
    case "ECR_MNG":
      await client.query(
        `UPDATE ecr_mng SET status_cd = $1 WHERE objid = $2::numeric`,
        [status, targetObjId]
      ).catch(() => {});
      break;
    case "SALES_REQUEST":
      await client.query(
        `UPDATE sales_request_master SET status = $1 WHERE objid::varchar = $2::varchar`,
        [status, targetObjId]
      ).catch(() => {});
      break;
  }
}
