package com.zioinfo.kintex.visitor.membership;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
 * F-C6 관람객 멤버십 매퍼. tenant_id='KINTEX' 고정. 본인(user_id)만.
 */
@Mapper
public interface MembershipMapper {

    /** 내 멤버십(없으면 null → 서비스가 기본 GENERAL 생성). */
    @Select("""
            SELECT user_id       AS "userId",
                   visit_count   AS "visitCount",
                   buyer_verified AS "buyerVerified",
                   vip_grant     AS "vipGrant",
                   points,
                   to_char(last_visit_at, 'YYYY-MM-DD"T"HH24:MI:SS') AS "lastVisitAt"
            FROM visitor_membership
            WHERE tenant_id = 'KINTEX' AND user_id = #{userId}
            """)
    Map<String, Object> find(@Param("userId") String userId);

    /** 멤버십 초기화(기본값). */
    @Update("""
            INSERT INTO visitor_membership (tenant_id, user_id, visit_count, buyer_verified, vip_grant, points)
            VALUES ('KINTEX', #{userId}, 0, false, false, 0)
            ON CONFLICT (tenant_id, user_id) DO NOTHING
            """)
    void ensure(@Param("userId") String userId);

    /** 바이어 인증(데모: 셀프 인증 토글). */
    @Update("""
            UPDATE visitor_membership
            SET buyer_verified = #{verified}, updated_at = now()
            WHERE tenant_id = 'KINTEX' AND user_id = #{userId}
            """)
    void setBuyerVerified(@Param("userId") String userId, @Param("verified") boolean verified);

    /** 등급별 혜택 목록. */
    @Select("""
            SELECT benefit
            FROM membership_benefit
            WHERE tenant_id = 'KINTEX' AND tier = #{tier}
            ORDER BY seq
            """)
    List<String> benefits(@Param("tier") String tier);
}
