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

// 결재상신 (approval.xml: insertApprovalInfo + createRouteInfo + createInboxTaskInfo 대응)
// 원본 ApprovalService.createApprovalInfo() 로직 포팅
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  if (!body.target_objid || !body.target_type) {
    return NextResponse.json({ success: false, message: "결재 대상과 유형이 필요합니다." });
  }
  const approvers: { user_id: string; approval_type?: string }[] = body.approvers || [];
  if (approvers.length === 0) {
    return NextResponse.json({ success: false, message: "결재자를 지정하세요." });
  }

  const systemType = body.system_type || "PLM";

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

    // 1. APPROVAL 생성/재사용 — APPROVAL_SEQ 자동증가 (SELECT MAX+1)
    let approvalObjId: string;
    const existing = await client.query(
      `SELECT objid::text AS objid FROM approval
       WHERE target_objid = $1::numeric AND system_type = $2 AND status != 'complete'
       ORDER BY regdate DESC LIMIT 1`,
      [body.target_objid, systemType]
    );
    if (existing.rows.length > 0) {
      approvalObjId = existing.rows[0].objid;
      await client.query(
        `UPDATE approval SET status = 'inProcess' WHERE objid = $1::numeric`,
        [approvalObjId]
      );
    } else {
      approvalObjId = createObjectId();
      await client.query(
        `INSERT INTO approval (objid, target_objid, target_type, approval_seq, system_type, regdate, status)
         VALUES ($1::numeric, $2::numeric, $3,
           (SELECT COALESCE(MAX(approval_seq::numeric) + 1, 1) FROM approval),
           $4, now(), 'inProcess')`,
        [approvalObjId, body.target_objid, body.target_type, systemType]
      );
    }

    // 2. ROUTE 생성 — ROUTE_SEQ 자동증가
    const routeObjId = createObjectId();
    await client.query(
      `INSERT INTO route (objid, target_objid, approval_objid, route_seq,
         approval_title, approval_desc, system_type, writer, regdate, status)
       VALUES ($1::numeric, $2::numeric, $3::numeric,
         (SELECT COALESCE(MAX(route_seq::numeric) + 1, 1) FROM route),
         $4, $5, $6, $7, now(), 'inProcess')`,
      [routeObjId, body.target_objid, approvalObjId,
       body.approval_title || "결재 요청", body.approval_desc || "", systemType, user.userId]
    );

    // 3. INBOXTASK — normal 순차(1st=ready, 나머지=standby), help/ref=즉시 ready
    for (let i = 0; i < approvers.length; i++) {
      const a = approvers[i];
      const approvalType = a.approval_type || "normal";
      const isFirstNormal = approvalType === "normal" && i === 0;
      const isHelpOrRef = approvalType === "help" || approvalType === "ref";
      const status = (isFirstNormal || isHelpOrRef) ? "ready" : "standby";
      await client.query(
        `INSERT INTO inboxtask (objid, seq, approval_type, target_objid, approval_objid, route_objid,
           target_user_id, regdate, status)
         VALUES ($1::numeric, $2, $3, $4::numeric, $5::numeric, $6::numeric, $7, now(), $8)`,
        [createObjectId(), i + 1, approvalType, body.target_objid,
         approvalObjId, routeObjId, a.user_id, status]
      );
    }

    // 4. 대상 모듈 상태 업데이트 (XxxApprovalStatus 쿼리 대응)
    await updateTargetStatus(client, body.target_type, body.target_objid, "approvalRequest", user.userId);

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