package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ButtonActionStandardService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
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/admin/button-actions")
@RequiredArgsConstructor
public class ButtonActionStandardController {

    private final ButtonActionStandardService buttonActionStandardService;

    /**
     * GET /api/admin/button-actions
     * 버튼 액션 목록 조회
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getButtonActions(
            @RequestParam Map<String, Object> params) {
        List<Map<String, Object>> data = buttonActionStandardService.getButtonActions(params);
        return ResponseEntity.ok(ApiResponse.success(data, "버튼 액션 목록을 성공적으로 조회했습니다."));
    }

    /**
     * GET /api/admin/button-actions/categories
     * 버튼 액션 카테고리 목록 조회
     */
    @GetMapping("/categories")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getButtonActionCategories() {
        List<Map<String, Object>> data = buttonActionStandardService.getCategories(new HashMap<>());
        return ResponseEntity.ok(ApiResponse.success(data, "버튼 액션 카테고리 목록을 성공적으로 조회했습니다."));
    }

    /**
     * GET /api/admin/button-actions/{actionType}
     * 버튼 액션 단건 조회
     */
    @GetMapping("/{actionType}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getButtonAction(
            @PathVariable String actionType) {
        Map<String, Object> params = new HashMap<>();
        params.put("action_type", actionType);
        Map<String, Object> data = buttonActionStandardService.getButtonAction(params);
        if (data == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error("해당 버튼 액션을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(data, "버튼 액션 정보를 성공적으로 조회했습니다."));
    }

    /**
     * POST /api/admin/button-actions
     * 버튼 액션 생성
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> createButtonAction(
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        // 필수 필드 검증
        if (body.get("action_type") == null || body.get("action_name") == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("액션 타입과 이름은 필수입니다."));
        }
        body.put("created_by", userId);
        body.put("updated_by", userId);
        // selectButtonActionByType 에서 actionType 키 사용
        body.put("action_type", body.get("action_type"));

        Map<String, Object> data = buttonActionStandardService.createButtonAction(body);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(ApiResponse.success(data, "버튼 액션이 성공적으로 생성되었습니다."));
    }

    /**
     * PUT /api/admin/button-actions/sort-order/bulk
     * 정렬 순서 일괄 업데이트
     */
    @PutMapping("/sort-order/bulk")
    public ResponseEntity<ApiResponse<Void>> updateButtonActionSortOrder(
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        Object raw = body.get("button_actions");
        if (!(raw instanceof List)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("유효하지 않은 데이터 형식입니다."));
        }
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> items = (List<Map<String, Object>>) raw;
        buttonActionStandardService.updateSortOrder(items, userId);
        return ResponseEntity.ok(ApiResponse.success(null, "버튼 액션 정렬 순서가 성공적으로 업데이트되었습니다."));
    }

    /**
     * PUT /api/admin/button-actions/{actionType}
     * 버튼 액션 수정
     */
    @PutMapping("/{actionType}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateButtonAction(
            @PathVariable String actionType,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        body.put("action_type", actionType);
        body.put("updated_by", userId);
        Map<String, Object> data = buttonActionStandardService.updateButtonAction(body);
        if (data == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error("해당 버튼 액션을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(data, "버튼 액션이 성공적으로 수정되었습니다."));
    }

    /**
     * DELETE /api/admin/button-actions/{actionType}
     * 버튼 액션 삭제
     */
    @DeleteMapping("/{actionType}")
    public ResponseEntity<ApiResponse<Void>> deleteButtonAction(
            @PathVariable String actionType) {
        Map<String, Object> params = new HashMap<>();
        params.put("action_type", actionType);
        boolean deleted = buttonActionStandardService.deleteButtonAction(params);
        if (!deleted) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error("해당 버튼 액션을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "버튼 액션이 성공적으로 삭제되었습니다."));
    }
}
