package com.zioinfo.kintex.visitor.paymethod;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
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-B5 저장 결제수단 매퍼. tenant_id='KINTEX' 고정. 본인(user_id) 소유분만.
 * <p>보안(§0-3): 카드 원문 미보관 — brand·last4·pg_token(mock 빌링키)만.
 */
@Mapper
public interface PayMethodMapper {

    @Select("""
            SELECT id, kind, brand, last4,
                   is_default AS "isDefault", label,
                   to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS') AS "createdAt"
            FROM visitor_pay_method
            WHERE tenant_id = 'KINTEX' AND user_id = #{userId}
            ORDER BY is_default DESC, created_at DESC
            """)
    List<Map<String, Object>> listByUser(@Param("userId") String userId);

    /** 단건(본인 소유 검증 포함). 없으면 null. */
    @Select("""
            SELECT id, kind, brand, last4, pg_token AS "pgToken",
                   is_default AS "isDefault", label
            FROM visitor_pay_method
            WHERE tenant_id = 'KINTEX' AND user_id = #{userId} AND id = #{id}
            """)
    Map<String, Object> findOwned(@Param("userId") String userId, @Param("id") String id);

    @Insert("""
            INSERT INTO visitor_pay_method
                (tenant_id, id, user_id, kind, brand, last4, pg_token, is_default, label)
            VALUES
                ('KINTEX', #{id}, #{userId}, #{kind}, #{brand}, #{last4}, #{pgToken}, #{isDefault}, #{label})
            """)
    void insert(Map<String, Object> row);

    /** 사용자 전 수단 기본 해제(단일 기본 보장). */
    @Update("UPDATE visitor_pay_method SET is_default = false WHERE tenant_id='KINTEX' AND user_id = #{userId}")
    void clearDefault(@Param("userId") String userId);

    /** 지정 수단을 기본으로(본인 소유분만). */
    @Update("UPDATE visitor_pay_method SET is_default = true WHERE tenant_id='KINTEX' AND user_id = #{userId} AND id = #{id}")
    int setDefault(@Param("userId") String userId, @Param("id") String id);

    @Delete("DELETE FROM visitor_pay_method WHERE tenant_id='KINTEX' AND user_id = #{userId} AND id = #{id}")
    int delete(@Param("userId") String userId, @Param("id") String id);
}
