package com.zioinfo.kintex.visitor.contact;

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-C4 관람객 명함/컨택트 지갑 매퍼. tenant_id='KINTEX' 고정. 본인(owner) 지갑만.
 * <p>보안(§0-3): 연락처·이메일은 마스킹 저장(원문 미보관).
 */
@Mapper
public interface ContactMapper {

    /** 내 명함 카드. 없으면 null. */
    @Select("""
            SELECT user_id      AS "userId",
                   display_name AS "displayName",
                   company,
                   title,
                   email_masked AS "emailMasked",
                   phone_masked AS "phoneMasked",
                   share_token  AS "shareToken"
            FROM visitor_contact_card
            WHERE tenant_id = 'KINTEX' AND user_id = #{userId}
            """)
    Map<String, Object> findMyCard(@Param("userId") String userId);

    /** 명함 카드 upsert. */
    @Update("""
            INSERT INTO visitor_contact_card
                (tenant_id, user_id, display_name, company, title, email_masked, phone_masked, share_token, updated_at)
            VALUES
                ('KINTEX', #{userId}, #{displayName}, #{company}, #{title}, #{emailMasked}, #{phoneMasked}, #{shareToken}, now())
            ON CONFLICT (tenant_id, user_id)
            DO UPDATE SET display_name = EXCLUDED.display_name,
                          company      = EXCLUDED.company,
                          title        = EXCLUDED.title,
                          email_masked = EXCLUDED.email_masked,
                          phone_masked = EXCLUDED.phone_masked,
                          updated_at   = now()
            """)
    void upsertMyCard(Map<String, Object> row);

    /** 공유 토큰으로 상대 명함 조회(교환 매개). 없으면 null. */
    @Select("""
            SELECT user_id      AS "userId",
                   display_name AS "displayName",
                   company,
                   title,
                   email_masked AS "emailMasked",
                   phone_masked AS "phoneMasked"
            FROM visitor_contact_card
            WHERE tenant_id = 'KINTEX' AND share_token = #{shareToken}
            """)
    Map<String, Object> findCardByShareToken(@Param("shareToken") String shareToken);

    /** 컨택트 저장(교환). 중복(owner,contact)은 무시. */
    @Insert("""
            INSERT INTO visitor_contact
                (tenant_id, id, owner_user_id, contact_user_id, display_name, company, title, email_masked, phone_masked, memo)
            VALUES
                ('KINTEX', #{id}, #{ownerUserId}, #{contactUserId}, #{displayName}, #{company}, #{title}, #{emailMasked}, #{phoneMasked}, #{memo})
            ON CONFLICT (owner_user_id, contact_user_id) DO NOTHING
            """)
    void insertContact(Map<String, Object> row);

    /** 내 지갑 목록(최신순). */
    @Select("""
            SELECT id,
                   contact_user_id AS "contactUserId",
                   display_name AS "displayName",
                   company,
                   title,
                   email_masked AS "emailMasked",
                   phone_masked AS "phoneMasked",
                   memo,
                   to_char(saved_at, 'YYYY-MM-DD"T"HH24:MI:SS') AS "savedAt"
            FROM visitor_contact
            WHERE tenant_id = 'KINTEX' AND owner_user_id = #{userId}
            ORDER BY saved_at DESC
            """)
    List<Map<String, Object>> listContacts(@Param("userId") String userId);

    @Delete("DELETE FROM visitor_contact WHERE tenant_id='KINTEX' AND owner_user_id = #{userId} AND id = #{id}")
    int deleteContact(@Param("userId") String userId, @Param("id") String id);
}
