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

// approval/getApprovalCnt.do 대응
export async function GET() {
  const user = await getSession();
  if (!user) return NextResponse.json({ count: 0 });

  try {
    // 원본 getApprovalCnt: INBOXTASK + APPROVAL + ROUTE JOIN,
    // SYSTEM_TYPE='PLM' + INBOX.STATUS='READY' + ROUTE.STATUS='inProcess'
    const result = await queryOne<{ CNT: string }>(
      `SELECT COUNT(1) AS "CNT"
       FROM inboxtask INBOX, approval APP, route ROU
       WHERE INBOX.target_user_id = $1
         AND INBOX.approval_objid = APP.objid
         AND INBOX.route_objid = ROU.objid
         AND APP.system_type = 'PLM'
         AND UPPER(INBOX.status) = 'READY'
         AND ROU.status = 'inProcess'`,
      [user.userId]
    );
    return NextResponse.json({ count: Number(result?.CNT || 0) });
  } catch {
    return NextResponse.json({ count: 0 });
  }
}
