package com.zioinfo.mall.member;

import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.integration.CrmClient;
import com.zioinfo.mall.integration.ItsmSecuritySanitizer;
import com.zioinfo.mall.member.mapper.MemberMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.Map;

/** 회원 API — /api/mall/member. 본인 프로필 + CRM 인사이트 연계(새니타이즈). */
@RestController
@RequestMapping("/api/mall/member")
@RequiredArgsConstructor
public class MemberController {

    private final MemberMapper mapper;
    private final CrmClient crmClient;

    @GetMapping("/me")
    public ApiResponse<MallMember> me(Authentication auth) {
        return ApiResponse.ok(mapper.findByUsername(auth.getName()));
    }

    @PutMapping("/me")
    public ApiResponse<MallMember> update(@RequestBody MallMember m, Authentication auth) {
        m.setUsername(auth.getName());
        mapper.upsert(m);
        return ApiResponse.ok(mapper.findByUsername(auth.getName()));
    }

    /** CRM 고객 인사이트(구매 성향) — 응답은 ItsmSecuritySanitizer로 정제. */
    @GetMapping("/me/insight")
    public ApiResponse<Map<String, Object>> insight(Authentication auth) {
        Map<String, Object> raw = crmClient.getCustomerInsight(auth.getName());
        Object cleaned = ItsmSecuritySanitizer.clean(raw == null ? new LinkedHashMap<>() : raw);
        @SuppressWarnings("unchecked")
        Map<String, Object> safe = (Map<String, Object>) cleaned;
        return ApiResponse.ok(safe);
    }
}
