import { Router, Request, Response } from "express";
import { authenticateToken } from "../middleware/authMiddleware";
import { getPool } from "../database/db";
import { logger } from "../utils/logger";

const router = Router();
router.use(authenticateToken);

/**
 * 영업관리 4개 메뉴(견적/주문/판매/매출) 공통 옵션 endpoint.
 * - 공통코드(comm_code)는 wace_plm parent_code_id 그룹 키로 조회
 * - 품목(item_info)은 wace 마이그레이션 데이터(company_code 비어있음) +
 *   현재 운영 회사 데이터 모두 노출
 */

/** GET /api/sales/codes/:groupId  →  [{code, label, sort}] */
router.get("/codes/:groupId", async (req: Request, res: Response) => {
  try {
    const { groupId } = req.params;
    const pool = getPool();
    const result = await pool.query(
      `SELECT code_id AS code, code_name AS label, sort_order AS sort
       FROM comm_code
       WHERE parent_code_id = $1
         AND status = 'active'
       ORDER BY sort_order, code_name`,
      [groupId],
    );
    res.json({ success: true, data: result.rows });
  } catch (err) {
    logger.error("salesCommon /codes error", err);
    res.status(500).json({ success: false, message: (err as Error).message });
  }
});

/** GET /api/sales/parts  →  [{id, item_number, item_name}] (영업관리 풀-옵션용)
 *  데이터 출처: wace 품목 마스터 전용 테이블 part_mng (8,176건).
 *  반환 키는 기존 호환을 위해 id/item_number/item_name으로 alias.
 *  status는 active/release/활성만 (wace 운영 값).
 */
router.get("/parts", async (_req: Request, res: Response) => {
  try {
    const pool = getPool();
    const result = await pool.query(
      `SELECT objid::varchar AS id,
              part_no        AS item_number,
              part_name      AS item_name
       FROM part_mng
       WHERE LOWER(COALESCE(status, '')) IN ('active', 'release', '활성')
         AND part_no   IS NOT NULL AND part_no   <> ''
         AND part_name IS NOT NULL AND part_name <> ''
       ORDER BY part_no NULLS LAST, part_name NULLS LAST`,
    );
    res.json({ success: true, data: result.rows });
  } catch (err) {
    logger.error("salesCommon /parts error", err);
    res.status(500).json({ success: false, message: (err as Error).message });
  }
});

/** GET /api/sales/customers  →  [{id, customer_name, customer_code}] */
router.get("/customers", async (_req: Request, res: Response) => {
  try {
    const pool = getPool();
    const result = await pool.query(
      `SELECT id, customer_name, customer_code
       FROM customer_mng
       WHERE customer_name IS NOT NULL AND customer_name <> ''
       ORDER BY customer_name`,
    );
    res.json({ success: true, data: result.rows });
  } catch (err) {
    logger.error("salesCommon /customers error", err);
    res.status(500).json({ success: false, message: (err as Error).message });
  }
});

export default router;
