package com.erp.controller;

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

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

@RestController
@RequestMapping("/api/favorites")
@RequiredArgsConstructor
@Slf4j
public class FavoritesController {

    private final FavoritesService favoritesService;

    /**
     * GET /api/favorites/menus
     * 로그인 사용자의 즐겨찾기 메뉴 목록.
     */
    @GetMapping("/menus")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getMyFavorites(
            @RequestAttribute("user_id") String userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        return ResponseEntity.ok(ApiResponse.success(
                favoritesService.getFavoriteMenuList(params),
                "즐겨찾기 메뉴 조회 성공"));
    }

    /**
     * POST /api/favorites/menus
     * 즐겨찾기 추가. body: { menu_objid, sort_order? }
     */
    @PostMapping("/menus")
    public ResponseEntity<ApiResponse<Map<String, Object>>> addFavorite(
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        Object menuObjid = body.get("menu_objid");
        if (menuObjid == null || String.valueOf(menuObjid).isBlank()) {
            return ResponseEntity.badRequest().body(ApiResponse.error("menu_objid 필수입니다."));
        }
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("menu_objid", String.valueOf(menuObjid));
        params.put("sort_order", body.get("sort_order"));
        return ResponseEntity.ok(ApiResponse.success(
                favoritesService.insertFavorite(params),
                "즐겨찾기 추가 성공"));
    }

    /**
     * DELETE /api/favorites/menus/{menuObjid}
     * 즐겨찾기 제거.
     */
    @DeleteMapping("/menus/{menuObjid}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> removeFavorite(
            @RequestAttribute("user_id") String userId,
            @PathVariable String menuObjid) {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("menu_objid", menuObjid);
        int affected = favoritesService.deleteFavorite(params);
        Map<String, Object> result = new HashMap<>();
        result.put("deleted", affected);
        return ResponseEntity.ok(ApiResponse.success(result, "즐겨찾기 제거 성공"));
    }
}
