package com.tasteby.service;

import com.tasteby.domain.DaemonConfig;
import com.tasteby.mapper.DaemonConfigMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.Map;

@Service
public class DaemonConfigService {

    private final DaemonConfigMapper mapper;

    public DaemonConfigService(DaemonConfigMapper mapper) {
        this.mapper = mapper;
    }

    public DaemonConfig getConfig() {
        return mapper.getConfig();
    }

    public void updateConfig(Map<String, Object> body) {
        DaemonConfig current = mapper.getConfig();
        if (current == null) return;

        if (body.containsKey("scan_enabled")) {
            current.setScanEnabled(Boolean.TRUE.equals(body.get("scan_enabled")));
        }
        if (body.containsKey("scan_interval_min")) {
            // #275 — 0/음수 입력으로 30초 사이클 폭주 방지. ClassCastException 대신 400.
            current.setScanIntervalMin(requirePositiveInt(body.get("scan_interval_min"), "scan_interval_min"));
        }
        if (body.containsKey("process_enabled")) {
            current.setProcessEnabled(Boolean.TRUE.equals(body.get("process_enabled")));
        }
        if (body.containsKey("process_interval_min")) {
            current.setProcessIntervalMin(requirePositiveInt(body.get("process_interval_min"), "process_interval_min"));
        }
        if (body.containsKey("process_limit")) {
            current.setProcessLimit(requirePositiveInt(body.get("process_limit"), "process_limit"));
        }
        mapper.updateConfig(current);
    }

    /** #275 — 양의 정수 가드. 비숫자/0/음수는 400. */
    private static int requirePositiveInt(Object raw, String field) {
        if (!(raw instanceof Number n)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, field + "은(는) 정수여야 합니다");
        }
        int v = n.intValue();
        if (v < 1) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, field + "은(는) 1 이상이어야 합니다 (폭주 방지)");
        }
        return v;
    }

    public void updateLastScan() {
        mapper.updateLastScan();
    }

    public void updateLastProcess() {
        mapper.updateLastProcess();
    }
}
