import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { getSession } from "@/lib/session";
import { updateTargetStatus } from "@/lib/approval-target";

// 결재 승인 (approval.xml: setInboxtaskResult + getNextApprovalObjId +
//   setNextInboxtaskStatus + getNotCompleteInboxtaskCnt + completeRoute + completeApproval 대응)
// 원본 ApprovalService.setApprovalResult + completeRouteInfo
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const inboxObjId = body.inboxObjId;
  if (!inboxObjId) return NextResponse.json({ success: false, message: "inboxObjId 필요" });

  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    // 1. 현재 결재자 검증
    const cur = await client.query(
      `SELECT IT.*, A.target_objid, A.target_type, A.objid AS approval_objid, R.objid AS route_objid
       FROM inboxtask IT
       JOIN approval A ON A.objid = IT.approval_objid
       LEFT JOIN route R ON R.objid = IT.route_objid
       WHERE IT.objid = $1::numeric AND IT.target_user_id = $2 AND IT.status = 'ready'`,
      [inboxObjId, user.userId]
    );
    if (cur.rows.length === 0) {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "결재 권한이 없거나 이미 처리된 건입니다." });
    }
    const task = cur.rows[0];

    // setInboxtaskResult — RESULT='Y' (원본), STATUS='complete'
    await client.query(
      `UPDATE inboxtask SET result = 'Y', status = 'complete', proc_date = now(), result_message = $1,
         sign = $2, sign_width = $3, sign_height = $4
       WHERE objid = $5::numeric`,
      [body.message || "", body.sign || null, body.sign_width || null, body.sign_height || null, inboxObjId]
    );

    // 2. 다음 차례의 normal 결재자가 있는지 — APPROVAL_TYPE='normal' + seq+1
    // getNextApprovalObjId 대응
    const next = await client.query(
      `SELECT objid FROM inboxtask
       WHERE UPPER(approval_type) = 'NORMAL'
         AND approval_objid = $1::numeric AND route_objid = $2::numeric
         AND seq::numeric = $3::numeric + 1`,
      [task.approval_objid, task.route_objid, task.seq]
    );
    if ((next.rowCount ?? 0) > 0) {
      // 다음 결재자 ready로 변경 (setNextInboxtaskStatus)
      await client.query(
        `UPDATE inboxtask SET status = 'ready', regdate = now() WHERE objid = $1::numeric`,
        [next.rows[0].objid]
      );
    }

    // 3. route별 남은 결재자(ready/standby) 없으면 완료 처리
    // getNotCompleteInboxtaskCnt 대응
    const remaining = await client.query(
      `SELECT COUNT(*)::int AS cnt FROM inboxtask
       WHERE route_objid = $1::numeric AND status IN ('ready', 'standby')`,
      [task.route_objid]
    );
    if (remaining.rows[0].cnt === 0) {
      // completeRoute + completeApproval
      await client.query(
        `UPDATE route SET status = 'complete' WHERE objid = $1::numeric`,
        [task.route_objid]
      );
      await client.query(
        `UPDATE approval SET status = 'complete', complete_date = now() WHERE objid = $1::numeric`,
        [task.approval_objid]
      );
      // 대상 모듈 approvalComplete (XxxApprovalStatus)
      await updateTargetStatus(client, task.target_type, String(task.target_objid), "approvalComplete", user.userId);
    }

    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: "결재 승인되었습니다." });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("Approve:", e);
    return NextResponse.json({ success: false, message: "승인 중 오류가 발생했습니다." }, { status: 500 });
  } finally { client.release(); }
}
