package com.zioinfo.kintex.system.commoncode;

import org.springframework.stereotype.Service;

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

/** 공통코드 조회/관리. 도메인 모듈은 하드코딩 대신 본 서비스를 통해 코드 조회(§7-4). */
@Service
public class CommonCodeService {

    private final CommonCodeMapper mapper;

    public CommonCodeService(CommonCodeMapper mapper) {
        this.mapper = mapper;
    }

    public List<CodeGroupDto> groups() {
        return mapper.findGroups().stream().map(r -> new CodeGroupDto(
                str(r.get("grpCode")), str(r.get("grpName")), str(r.get("description")),
                str(r.get("useYn")), intVal(r.get("sortOrder")))).toList();
    }

    public List<CodeDto> codes(String grpCode) {
        return mapper.findCodes(grpCode).stream().map(r -> new CodeDto(
                str(r.get("grpCode")), str(r.get("code")), str(r.get("codeName")),
                str(r.get("codeValue")), intVal(r.get("sortOrder")), str(r.get("useYn")),
                str(r.get("attr1")))).toList();
    }

    public void saveGroup(CodeGroupDto g) {
        Map<String, Object> p = new HashMap<>();
        p.put("grpCode", g.grpCode());
        p.put("grpName", g.grpName());
        p.put("description", g.description());
        p.put("useYn", g.useYn());
        p.put("sortOrder", g.sortOrder());
        mapper.upsertGroup(p);
    }

    public void deleteGroup(String grpCode) {
        mapper.deleteGroup(grpCode);
    }

    public void saveCode(CodeDto c) {
        Map<String, Object> p = new HashMap<>();
        p.put("grpCode", c.grpCode());
        p.put("code", c.code());
        p.put("codeName", c.codeName());
        p.put("codeValue", c.codeValue());
        p.put("sortOrder", c.sortOrder());
        p.put("useYn", c.useYn());
        p.put("attr1", c.attr1());
        mapper.upsertCode(p);
    }

    public void deleteCode(String grpCode, String code) {
        mapper.deleteCode(grpCode, code);
    }

    private static String str(Object o) { return o == null ? null : String.valueOf(o); }
    private static int intVal(Object o) {
        if (o instanceof Number n) return n.intValue();
        try { return o == null ? 0 : Integer.parseInt(String.valueOf(o)); }
        catch (NumberFormatException e) { return 0; }
    }
}
