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

// 동일 target_objid 에 대한 결재번호/이력 목록 (approvalDetail.jsp 의 routeNo 드롭다운)
// 상신 → 반려 → 재상신 흐름 시 이전 라우트들을 보존하므로 여러 건 존재 가능
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { targetObjId, approvalObjId } = await request.json();
  if (!targetObjId && !approvalObjId) {
    return NextResponse.json({ success: false, message: "targetObjId 또는 approvalObjId 필요" });
  }

  // targetObjId 가 있으면 같은 target 의 모든 route 이력
  // approvalObjId 만 있으면 같은 approval 의 모든 route 이력
  const sql = targetObjId
    ? `SELECT R.objid::text AS "ROUTE_OBJID",
              A.objid::text AS "APPROVAL_OBJID",
              'APPROVAL-' || LPAD(A.approval_seq::text, 4, '0') AS "APPROVAL_NO",
              'ROUTE-' || LPAD(R.route_seq::text, 4, '0') AS "ROUTE_NO",
              R.status AS "STATUS",
              R.approval_title AS "TITLE",
              TO_CHAR(R.regdate, 'YYYY-MM-DD HH24:MI') AS "REGDATE"
         FROM approval A
         JOIN route R ON R.approval_objid = A.objid
        WHERE A.target_objid = $1::numeric
        ORDER BY R.regdate DESC`
    : `SELECT R.objid::text AS "ROUTE_OBJID",
              A.objid::text AS "APPROVAL_OBJID",
              'APPROVAL-' || LPAD(A.approval_seq::text, 4, '0') AS "APPROVAL_NO",
              'ROUTE-' || LPAD(R.route_seq::text, 4, '0') AS "ROUTE_NO",
              R.status AS "STATUS",
              R.approval_title AS "TITLE",
              TO_CHAR(R.regdate, 'YYYY-MM-DD HH24:MI') AS "REGDATE"
         FROM approval A
         JOIN route R ON R.approval_objid = A.objid
        WHERE A.objid = $1::numeric
        ORDER BY R.regdate DESC`;

  const rows = await queryRows(sql, [String(targetObjId || approvalObjId)]);
  return NextResponse.json({ RESULTLIST: rows });
}
