package com.zioinfo.kintex.work.stats;

import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.system.SystemAccessGuard;
import org.springframework.stereotype.Service;

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

/** 업무 통계 서비스 — worklog 집계(상태·유형·작성자). DataScope 적용. */
@Service
public class StatsService {

    private final StatsMapper mapper;
    private final SystemAccessGuard scope;

    public StatsService(StatsMapper mapper, SystemAccessGuard scope) {
        this.mapper = mapper;
        this.scope = scope;
    }

    public WorkStatsDto workStats(KintexPrincipal principal, String eventId, String fromDate, String toDate) {
        Map<String, Object> q = new HashMap<>();
        q.put("mineOnly", !scope.canSeeAll(principal));
        q.put("userId", principal.userId());
        q.put("eventId", eventId);
        q.put("fromDate", fromDate);
        q.put("toDate", toDate);
        Map<String, Object> sum = mapper.summary(q);
        long totalCount = lng(sum.get("count"));
        double totalHours = dbl(sum.get("hours"));
        return new WorkStatsDto(totalCount, totalHours,
                toItems(mapper.byStatus(q)), toItems(mapper.byType(q)), toItems(mapper.byWriter(q)));
    }

    private static List<StatItem> toItems(List<Map<String, Object>> rows) {
        return rows.stream().map(r -> new StatItem(
                str(r.get("name")), lng(r.get("count")), dbl(r.get("hours")))).toList();
    }
    private static String str(Object o) { return o == null ? null : String.valueOf(o); }
    private static long lng(Object o) {
        if (o instanceof Number n) return n.longValue();
        try { return o == null ? 0 : Long.parseLong(String.valueOf(o)); }
        catch (NumberFormatException e) { return 0; }
    }
    private static double dbl(Object o) {
        if (o instanceof Number n) return n.doubleValue();
        try { return o == null ? 0 : Double.parseDouble(String.valueOf(o)); }
        catch (NumberFormatException e) { return 0; }
    }
}
