package com.zioinfo.kintex.visitor.membership;

import com.zioinfo.kintex.visitor.membership.MembershipDtos.MembershipDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * F-C6 관람객 멤버십 서비스 — 재방문·바이어 인증 기반 등급 산정 + 혜택 표시.
 * 등급 규칙은 {@link MembershipTier}(순수 함수) 위임.
 */
@Service
public class MembershipService {

    private final MembershipMapper mapper;

    public MembershipService(MembershipMapper mapper) {
        this.mapper = mapper;
    }

    /** 내 멤버십 — 없으면 기본 GENERAL 생성 후 산정. */
    @Transactional
    public MembershipDto myMembership(String userId) {
        Map<String, Object> m = mapper.find(userId);
        if (m == null) {
            mapper.ensure(userId);
            m = mapper.find(userId);
        }
        return build(m);
    }

    /** 바이어 인증 토글(데모 셀프 인증) — 실제는 사업자/명함 검증 연계. */
    @Transactional
    public MembershipDto setBuyerVerified(String userId, boolean verified) {
        mapper.ensure(userId);
        mapper.setBuyerVerified(userId, verified);
        return build(mapper.find(userId));
    }

    private MembershipDto build(Map<String, Object> m) {
        int visits = toInt(m.get("visitCount"), 0);
        boolean buyer = bool(m.get("buyerVerified"));
        boolean vip = bool(m.get("vipGrant"));
        String tier = MembershipTier.of(visits, buyer, vip);
        return new MembershipDto(
                tier, MembershipTier.label(tier), visits, buyer, vip,
                toInt(m.get("points"), 0), str(m.get("lastVisitAt")),
                MembershipTier.visitsToNextTier(tier, visits), mapper.benefits(tier));
    }

    private static String str(Object o) {
        return o == null ? null : o.toString();
    }

    private static boolean bool(Object o) {
        return o instanceof Boolean b && b;
    }

    private static int toInt(Object o, int def) {
        return o instanceof Number n ? n.intValue() : def;
    }
}
