package com.erp.service;

import com.erp.common.BaseService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class UserOverrideService extends BaseService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String NS = "userOverride.";

    public Map<String, Object> getUserOverride(Map<String, Object> params) {
        Map<String, Object> row = sqlSession.selectOne(NS + "getUserOverride", params);
        if (row != null) {
            parseJsonField(row, "overrides");
        }
        return row;
    }

    @Transactional
    public void upsertUserOverride(Map<String, Object> params) {
        if (params.get("override_id") == null) {
            String overrideId = "ovr_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
            params.put("override_id", overrideId);
        }
        stringifyJsonField(params, "overrides");
        sqlSession.insert(NS + "upsertUserOverride", params);
    }

    @Transactional
    public void deleteUserOverride(Map<String, Object> params) {
        sqlSession.delete(NS + "deleteUserOverride", params);
    }

    private void parseJsonField(Map<String, Object> row, String key) {
        Object val = row.get(key);
        if (val instanceof String) {
            try {
                row.put(key, objectMapper.readValue((String) val, Object.class));
            } catch (Exception e) {
                log.warn("JSON parse failed: key={}", key);
            }
        }
    }

    private void stringifyJsonField(Map<String, Object> params, String key) {
        Object val = params.get(key);
        if (val != null && !(val instanceof String)) {
            try {
                params.put(key, objectMapper.writeValueAsString(val));
            } catch (Exception e) {
                log.warn("JSON stringify failed: key={}", key);
            }
        }
    }
}
