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

// 신규 모모 메뉴를 menu_info / authority_sub_menu 에 자동 등록
// (db/migrations 자동 실행이 빠진 상태에서 코드만 push 해도 사이드바에 노출되도록)
let menusEnsured = false;
async function ensureMomoMenus() {
  if (menusEnsured) return;
  try {
    // 9000405 — 출고/정산 그룹(9000400) 산하 "일자별 발주/재고 현황"
    // menu_info 에는 objid PK 외에 unique constraint 가 없어, 우선 존재 여부 확인 후 분기.
    const exists = await queryRows<{ cnt: string }>(
      `SELECT COUNT(*)::text AS cnt FROM menu_info WHERE objid = 9000405`
    );
    if (Number(exists[0]?.cnt || "0") === 0) {
      await pool.query(
        `INSERT INTO menu_info (objid, menu_type, parent_obj_id, menu_name_kor, menu_name_eng,
                                seq, menu_url, status, system_name, regdate)
         VALUES (9000405, '1', 9000400, '일자별 발주/재고', 'Daily Order/Stock',
                 13, '/m/admin/daily-order-inventory', 'active', 'PMS', NOW())`
      );
    } else {
      await pool.query(
        `UPDATE menu_info
            SET parent_obj_id = 9000400,
                menu_name_kor = '일자별 발주/재고',
                menu_name_eng = 'Daily Order/Stock',
                menu_url      = '/m/admin/daily-order-inventory',
                status        = 'active'
          WHERE objid = 9000405`
      );
    }

    // 출고/정산(9000401 = 출고 관리) 권한을 가진 모든 master 에 자동 매핑
    const targets = await queryRows<{ MASTER_OBJID: string }>(
      `SELECT DISTINCT master_objid::text AS "MASTER_OBJID"
         FROM authority_sub_menu
        WHERE menu_objid = 9000401
          AND master_objid NOT IN (
            SELECT master_objid FROM authority_sub_menu WHERE menu_objid = 9000405
          )`
    );
    for (const t of targets) {
      await pool.query(
        `INSERT INTO authority_sub_menu (objid, master_objid, menu_objid, writer, regdate)
         SELECT $1::numeric, $2::numeric, 9000405, 'system', NOW()
         WHERE NOT EXISTS (
           SELECT 1 FROM authority_sub_menu WHERE master_objid = $2::numeric AND menu_objid = 9000405
         )`,
        [createObjectId(), t.MASTER_OBJID]
      );
    }
    menusEnsured = true;
  } catch (err) {
    console.error("[menu/ensureMomoMenus]", err);
  }
}

// main/getmenu.do 대응 — 사이드 메뉴 조회 (권한 그룹 필터 적용)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) {
    return NextResponse.json({ success: false }, { status: 401 });
  }
  await ensureMomoMenus();

  const body = await request.json();
  const menuObjId = body.MENUOBJID || "";

  // 로그인한 사용자의 권한 그룹에 매핑된 메뉴만 노출 (자식이 권한에 있으면 부모 자동 표시).
  // isAdmin 같은 백도어는 두지 않음 — 모든 사용자는 권한 그룹 매핑대로 동적으로 메뉴를 받는다.
  const rows = await queryRows(
    `SELECT MI.OBJID::text AS "objid",
            MI.MENU_NAME_KOR AS "menuNameKor",
            MI.MENU_NAME_ENG AS "menuNameEng",
            COALESCE(MI.MENU_URL, '') AS "menuUrl",
            MI.PARENT_OBJ_ID::text AS "parentObjId",
            MI.SEQ::text AS "menuOrder",
            CASE WHEN MI.PARENT_OBJ_ID = $1::numeric THEN '1' ELSE '2' END AS "level"
     FROM MENU_INFO MI
     WHERE COALESCE(MI.STATUS, '') = 'active'
       AND (MI.PARENT_OBJ_ID = $1::numeric
            OR MI.PARENT_OBJ_ID IN (SELECT OBJID FROM MENU_INFO WHERE PARENT_OBJ_ID = $1::numeric AND COALESCE(STATUS, '') = 'active'))
       AND (
         MI.OBJID IN (
           SELECT ASM.menu_objid
           FROM authority_sub_user ASU
           JOIN authority_sub_menu ASM ON ASM.master_objid = ASU.master_objid
           WHERE ASU.user_id = $2::text
         )
         OR EXISTS (
           SELECT 1 FROM menu_info CH
           WHERE CH.parent_obj_id = MI.objid
             AND CH.objid IN (
               SELECT ASM.menu_objid
               FROM authority_sub_user ASU
               JOIN authority_sub_menu ASM ON ASM.master_objid = ASU.master_objid
               WHERE ASU.user_id = $2::text
             )
         )
       )
     ORDER BY MI.SEQ`,
    [menuObjId, user.userId]
  );

  return NextResponse.json({ RESULT: rows });
}
