package com.zioinfo.kintex.system.company;

import com.zioinfo.kintex.common.PageResponse;
import com.zioinfo.kintex.common.error.ApiException;
import com.zioinfo.kintex.common.error.ErrorCode;
import com.zioinfo.kintex.common.text.Masking;
import com.zioinfo.kintex.tenant.TenantContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/** 회사(거래처) 관리 서비스. 연락처는 마스킹 후 응답(§0-3). 테넌트 스코프. */
@Service
public class CompanyService {

    private final CompanyMapper mapper;

    public CompanyService(CompanyMapper mapper) {
        this.mapper = mapper;
    }

    public PageResponse<CompanyDto> list(String keyword, String partnerType, int page, int size) {
        int p = Math.max(page, 0);
        int s = size <= 0 ? 20 : Math.min(size, 200);
        String tenantId = TenantContext.currentTenantId();
        List<Map<String, Object>> rows = mapper.search(tenantId, keyword, partnerType, s, p * s);
        long total = mapper.count(tenantId, keyword, partnerType);
        return PageResponse.of(rows.stream().map(CompanyService::toDto).toList(), p, s, total);
    }

    @Transactional
    public void save(CompanySaveRequest req) {
        String id = (req.id() == null || req.id().isBlank())
                ? "co-" + UUID.randomUUID().toString().substring(0, 12) : req.id();
        Map<String, Object> pm = new HashMap<>();
        pm.put("tenantId", TenantContext.currentTenantId());
        pm.put("id", id);
        pm.put("companyName", req.companyName());
        pm.put("bizNo", req.bizNo());
        pm.put("ceoName", req.ceoName());
        pm.put("bizType", req.bizType());
        pm.put("contactName", req.contactName());
        pm.put("contactTel", req.contactTel());
        pm.put("address", req.address());
        pm.put("partnerType", req.partnerType());
        pm.put("useYn", req.useYn());
        mapper.upsert(pm);
    }

    @Transactional
    public void delete(String id) {
        if (mapper.delete(TenantContext.currentTenantId(), id) == 0) {
            throw new ApiException(ErrorCode.NOT_FOUND);
        }
    }

    private static CompanyDto toDto(Map<String, Object> r) {
        return new CompanyDto(
                str(r.get("id")), str(r.get("companyName")), str(r.get("bizNo")), str(r.get("ceoName")),
                str(r.get("bizType")), str(r.get("contactName")), Masking.maskPhone(str(r.get("contactTel"))),
                str(r.get("address")), str(r.get("partnerType")), str(r.get("useYn")));
    }
    private static String str(Object o) { return o == null ? null : String.valueOf(o); }
}
