<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="favorites">

  <!-- ================================================================
       사용자별 메뉴 즐겨찾기
       USER_MENU_FAVORITES (USER_ID, MENU_OBJID) UNIQUE
       ================================================================ -->

  <!-- 내 즐겨찾기 메뉴 목록 (MENU_INFO 와 JOIN, 활성 메뉴만) -->
  <select id="selectFavoriteMenuList" parameterType="map" resultType="map">
    SELECT
        UMF.OBJID         AS favorite_objid
      , UMF.USER_ID       AS user_id
      , UMF.MENU_OBJID    AS menu_objid
      , UMF.SORT_ORDER    AS sort_order
      , UMF.CREATED_AT    AS created_at
      , MENU.MENU_NAME_KOR AS menu_name_kor
      , MENU.MENU_URL      AS menu_url
      , MENU.MENU_ICON     AS menu_icon
      , MENU.PARENT_OBJ_ID AS parent_obj_id
      , MENU.MENU_TYPE     AS menu_type
      , MENU.COMPANY_CODE  AS company_code
    FROM USER_MENU_FAVORITES UMF
    JOIN MENU_INFO MENU ON MENU.OBJID = UMF.MENU_OBJID
    WHERE UMF.USER_ID = #{user_id}
      AND MENU.STATUS = 'active'
    ORDER BY UMF.SORT_ORDER ASC, UMF.CREATED_AT ASC
  </select>

  <!-- 즐겨찾기 추가 (이미 있으면 무시) -->
  <insert id="insertFavorite" parameterType="map">
    INSERT INTO USER_MENU_FAVORITES (USER_ID, MENU_OBJID, SORT_ORDER)
    VALUES (#{user_id}, #{menu_objid}, COALESCE(#{sort_order}, 0))
    ON CONFLICT (USER_ID, MENU_OBJID) DO NOTHING
  </insert>

  <!-- 즐겨찾기 제거 -->
  <delete id="deleteFavorite" parameterType="map">
    DELETE FROM USER_MENU_FAVORITES
    WHERE USER_ID = #{user_id}
      AND MENU_OBJID = #{menu_objid}
  </delete>

  <!-- 단건 존재 확인 (toggle 동작에 활용) -->
  <select id="selectFavoriteExists" parameterType="map" resultType="int">
    SELECT COUNT(*) FROM USER_MENU_FAVORITES
    WHERE USER_ID = #{user_id}
      AND MENU_OBJID = #{menu_objid}
  </select>

</mapper>
