package com.erp.service;

import com.erp.common.BaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class TodoService extends BaseService {

    private final CommonService commonService;

    private static final String NS = "todo.";

    public Map<String, Object> getTodoList(Map<String, Object> params) {
        commonService.applyPagination(params);
        Integer totalObj = sqlSession.selectOne(NS + "getTodoListCnt", params);
        int totalCount = totalObj != null ? totalObj : 0;
        List<Map<String, Object>> list = sqlSession.selectList(NS + "getTodoList", params);

        // stats 계산
        Map<String, Object> stats = new LinkedHashMap<>();
        stats.put("total", totalCount);
        long pending = list.stream().filter(t -> "pending".equals(t.get("status"))).count();
        long inProgress = list.stream().filter(t -> "in_progress".equals(t.get("status"))).count();
        long completed = list.stream().filter(t -> "completed".equals(t.get("status"))).count();
        long urgent = list.stream().filter(t -> Boolean.TRUE.equals(t.get("is_urgent"))).count();
        stats.put("pending", pending);
        stats.put("in_progress", inProgress);
        stats.put("completed", completed);
        stats.put("urgent", urgent);

        Map<String, Object> result = commonService.buildListResponse(list, totalCount, params);
        result.put("stats", stats);
        return result;
    }

    public Map<String, Object> getTodoInfo(Map<String, Object> params) {
        return sqlSession.selectOne(NS + "getTodoInfo", params);
    }

    @Transactional
    public Map<String, Object> insertTodo(Map<String, Object> params) {
        String id = UUID.randomUUID().toString();
        params.put("id", id);
        sqlSession.insert(NS + "insertTodo", params);
        return sqlSession.selectOne(NS + "getTodoInfo", Map.of("id", id));
    }

    @Transactional
    public Map<String, Object> updateTodo(Map<String, Object> params) {
        sqlSession.update(NS + "updateTodo", params);
        return sqlSession.selectOne(NS + "getTodoInfo", Map.of("id", params.get("id")));
    }

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

    @Transactional
    public void reorderTodos(List<String> todoIds) {
        for (int i = 0; i < todoIds.size(); i++) {
            Map<String, Object> p = new HashMap<>();
            p.put("id", todoIds.get(i));
            p.put("display_order", i);
            sqlSession.update(NS + "updateTodoOrder", p);
        }
    }
}
