import { NextRequest, NextResponse } from "next/server";
import { queryOne, queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

// CS 단건 조회 (getCSMInfo + getCSPList + getCSWList 대응)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { objId } = await request.json();
  if (!objId) return NextResponse.json({ success: false, message: "objId required" });

  const info = await queryOne(
    `SELECT CSM.objid::text AS "OBJID",
            CSM.service_no AS "SERVICE_NO",
            CSM.product AS "PRODUCT",
            (SELECT code_name FROM comm_code WHERE code_id = CSM.product) AS "PRODUCT_NAME",
            CSM.contract_objid AS "CONTRACT_OBJID",
            CSM.cs_category AS "CS_CATEGORY",
            (SELECT code_name FROM comm_code WHERE code_id = CSM.cs_category) AS "CATEGORY_NAME",
            CSM.warranty AS "WARRANTY",
            (SELECT code_name FROM comm_code WHERE code_id = CSM.warranty) AS "WARRANTY_NAME",
            CSM.manager_id AS "MANAGER_ID",
            (SELECT user_name FROM user_info WHERE user_id = CSM.manager_id) AS "MANAGER_NAME",
            CSM.act_date AS "ACT_DATE",
            CSM.category_h AS "CATEGORY_H",
            CSM.category_m AS "CATEGORY_M",
            CSM.category_l AS "CATEGORY_L",
            (SELECT code_name FROM comm_code WHERE code_id = CSM.category_h) AS "CATEGORY_H_NAME",
            CSM.title AS "TITLE",
            CSM.before_contents AS "BEFORE_CONTENTS",
            CSM.after_contents AS "AFTER_CONTENTS",
            CSM.writer AS "WRITER",
            CSM.status AS "STATUS",
            (SELECT code_name FROM comm_code WHERE code_id = CSM.status) AS "STATUS_NAME",
            TO_CHAR(CSM.regdate, 'YYYY-MM-DD') AS "REC_DT",
            CM.project_no AS "PROJECT_NO",
            CM.customer_objid AS "CUSTOMER_OBJID",
            (SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid) AS "CUSTOMER_NAME",
            CM.setup AS "SETUP",
            RM.release_date AS "RELEASE_DATE",
            APPR.APPR_STATUS AS "APPR_STATUS",
            APPR.APPR_STATUS_NAME AS "APPR_STATUS_NAME",
            APPR.APPROVAL_OBJID AS "APPROVAL_OBJID",
            APPR.ROUTE_OBJID AS "ROUTE_OBJID"
       FROM customer_service_mgmt CSM
       LEFT JOIN project_mgmt CM ON CSM.contract_objid = CM.objid
       LEFT JOIN release_mgmt RM ON CM.objid = RM.parent_objid
       LEFT JOIN (
         SELECT B.objid AS ROUTE_OBJID,
                B.status AS APPR_STATUS,
                CASE UPPER(B.status)
                  WHEN 'INPROCESS' THEN '결재중'
                  WHEN 'COMPLETE'  THEN '결재완료'
                  WHEN 'REJECT'    THEN '반려'
                  ELSE '' END AS APPR_STATUS_NAME,
                A.objid AS APPROVAL_OBJID,
                A.target_objid
         FROM approval A,
              (SELECT T1.* FROM
                 (SELECT target_objid, MAX(route_seq) AS route_seq FROM route GROUP BY target_objid) T,
                 route T1
                WHERE T.target_objid = T1.target_objid AND T.route_seq = T1.route_seq) B
         WHERE A.objid = B.approval_objid AND A.target_type = 'CSM'
       ) APPR ON CSM.objid::numeric = APPR.target_objid
      WHERE CSM.objid = $1`,
    [objId]
  );

  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });

  const parts = await queryRows(
    `SELECT objid::text AS "OBJID", parent_objid AS "PARENT_OBJID",
            part_no AS "PART_NO", part_name AS "PART_NAME", spec AS "SPEC",
            qty AS "QTY", cur_qty AS "CUR_QTY", price AS "PRICE", sup_price AS "SUP_PRICE"
       FROM customer_service_part WHERE parent_objid = $1 ORDER BY objid`,
    [objId]
  );

  const works = await queryRows(
    `SELECT objid::text AS "OBJID", parent_objid AS "PARENT_OBJID",
            supply_objid AS "SUPPLY_OBJID", form_date AS "FORM_DATE", to_date AS "TO_DATE",
            work_day AS "WORK_DAY", work_person AS "WORK_PERSON", work_day_m AS "WORK_DAY_M",
            labor_cost AS "LABOR_COST", expenses AS "EXPENSES"
       FROM customer_service_workingtime WHERE parent_objid = $1 ORDER BY objid`,
    [objId]
  );

  return NextResponse.json({ success: true, data: info, parts, works });
}
