package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.TodoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/api/todo")
@RequiredArgsConstructor
@Slf4j
public class TodoController {

    private final TodoService todoService;

    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTodoList(
            @RequestParam Map<String, Object> params) {
        return ResponseEntity.ok(ApiResponse.success(todoService.getTodoList(params)));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertTodo(
            @RequestBody Map<String, Object> body) {
        Map<String, Object> result = todoService.insertTodo(body);
        return ResponseEntity.status(201).body(ApiResponse.success(result, "To-Do가 생성되었습니다."));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateTodo(
            @PathVariable String id,
            @RequestBody Map<String, Object> body) {
        body.put("id", id);
        return ResponseEntity.ok(ApiResponse.success(todoService.updateTodo(body), "To-Do가 수정되었습니다."));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteTodo(
            @PathVariable String id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        todoService.deleteTodo(params);
        return ResponseEntity.ok(ApiResponse.success(null, "To-Do가 삭제되었습니다."));
    }

    @PostMapping("/reorder")
    public ResponseEntity<ApiResponse<Map<String, Object>>> reorderTodos(
            @RequestBody Map<String, Object> body) {
        Object todoIdsObj = body.get("todo_ids");
        if (!(todoIdsObj instanceof List)) {
            return ResponseEntity.status(400).body(
                ApiResponse.error("todoIds는 배열이어야 합니다."));
        }
        List<String> todoIds = new ArrayList<>();
        for (Object id : (List<?>) todoIdsObj) {
            todoIds.add(String.valueOf(id));
        }
        todoService.reorderTodos(todoIds);
        return ResponseEntity.ok(ApiResponse.success(null, "To-Do 순서가 변경되었습니다."));
    }

    // 이전 호환
    @GetMapping("/list")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTodoListLegacy(
            @RequestParam Map<String, Object> params) {
        return ResponseEntity.ok(ApiResponse.success(todoService.getTodoList(params)));
    }
}
