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

// 결재 상세 + 결재선 (getApprovalLine 대응)
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" });

  // 원본 getRouteInfo 대응 — APPROVAL-NNNN/ROUTE-NNNN 번호, 이메일, 부서, reject 제외
  const info = await queryOne(
    `SELECT A.objid::text AS "OBJID", A.target_objid AS "TARGET_OBJID",
       A.target_type AS "TARGET_TYPE",
       A.approval_seq AS "APPROVAL_SEQ",
       'APPROVAL-' || LPAD(A.approval_seq::text, 4, '0') AS "APPROVAL_NO",
       A.status AS "STATUS",
       R.objid::text AS "ROUTE_OBJID",
       R.route_seq AS "ROUTE_SEQ",
       'ROUTE-' || LPAD(R.route_seq::text, 4, '0') AS "ROUTE_NO",
       R.approval_title AS "TITLE", R.approval_desc AS "DESCRIPTION",
       R.writer AS "WRITER",
       COALESCE((SELECT email FROM user_info WHERE user_id = R.writer LIMIT 1), '') AS "EMAIL",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = R.writer LIMIT 1), R.writer) AS "WRITER_NAME",
       COALESCE((SELECT dept_name FROM user_info WHERE user_id = R.writer LIMIT 1), '') AS "DEPT_NAME",
       TO_CHAR(A.regdate, 'YYYY-MM-DD HH24:MI') AS "REGDATE",
       TO_CHAR(A.complete_date, 'YYYY-MM-DD HH24:MI') AS "COMPLETE_DATE"
     FROM approval A
     LEFT JOIN route R ON R.approval_objid = A.objid AND R.status != 'reject'
     WHERE A.objid::text = $1
     ORDER BY R.regdate DESC LIMIT 1`, [objId]
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });

  // 결재선 (INBOXTASK)
  const line = await queryRows(
    `SELECT IT.objid::text AS "OBJID", IT.seq AS "SEQ",
       IT.target_user_id AS "USER_ID",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = IT.target_user_id LIMIT 1), IT.target_user_id) AS "USER_NAME",
       COALESCE((SELECT dept_name FROM user_info WHERE user_id = IT.target_user_id LIMIT 1), '') AS "DEPT_NAME",
       IT.approval_type AS "APPROVAL_TYPE",
       IT.status AS "STATUS",
       CASE IT.status
         WHEN 'ready' THEN '대기중'
         WHEN 'standby' THEN '대기'
         WHEN 'complete' THEN '승인'
         WHEN 'reject' THEN '반려'
         WHEN 'cancel' THEN '취소'
         ELSE IT.status END AS "STATUS_NAME",
       TO_CHAR(IT.proc_date, 'YYYY-MM-DD HH24:MI') AS "PROC_DATE",
       IT.result_message AS "RESULT_MESSAGE"
     FROM inboxtask IT
     WHERE IT.approval_objid::text = $1
     ORDER BY IT.seq::numeric`, [objId]
  );

  // 현재 사용자가 결재자인지 확인
  const myTask = line.find((l: Record<string, unknown>) =>
    l.USER_ID === user.userId && (l.STATUS === "ready")
  );

  return NextResponse.json({
    success: true, data: info, LINE: line,
    canApprove: !!myTask, myInboxObjId: myTask?.OBJID || null,
  });
}
