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 + cancelInboxtask +
//   updateRouteStatus + changeApprovalStatus 대응)
// 원본 ApprovalService.rejectRouteInfo
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");

    const cur = await client.query(
      `SELECT IT.*, A.target_objid, A.target_type
       FROM inboxtask IT
       JOIN approval A ON A.objid = IT.approval_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='N'(반려)
    await client.query(
      `UPDATE inboxtask SET result = 'N', status = 'reject', 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]
    );

    // cancelInboxtask — 해당 route의 reject/complete 아닌 건을 cancel
    await client.query(
      `UPDATE inboxtask SET status = 'cancel'
       WHERE status NOT IN ('complete', 'reject') AND route_objid = $1::numeric`,
      [task.route_objid]
    );

    // updateRouteStatus — reject
    await client.query(
      `UPDATE route SET status = 'reject' WHERE objid = $1::numeric`,
      [task.route_objid]
    );
    // changeApprovalStatus — reject
    await client.query(
      `UPDATE approval SET status = 'reject', complete_date = now() WHERE objid = $1::numeric`,
      [task.approval_objid]
    );

    // 대상 모듈 상태 반려 (XxxApprovalStatus)
    await updateTargetStatus(client, task.target_type, String(task.target_objid), "reject", user.userId);

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