package com.erp.controller;

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

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

@RestController
@RequestMapping("/api/db-type-categories")
@RequiredArgsConstructor
@Slf4j
public class DbTypeCategoryController {

    private final DbTypeCategoryService dbTypeCategoryService;

    /**
     * GET /api/db-type-categories
     * 모든 DB 타입 카테고리 조회
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getAllCategories() {
        List<Map<String, Object>> categories = dbTypeCategoryService.getAllCategories();
        return ResponseEntity.ok(ApiResponse.success(categories, "DB 타입 카테고리 목록을 조회했습니다."));
    }

    /**
     * GET /api/db-type-categories/stats/connections
     * DB 타입별 연결 통계 조회
     * NOTE: /{typeCode} 보다 먼저 선언 — 리터럴 세그먼트 우선
     */
    @GetMapping("/stats/connections")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getConnectionStatsByType() {
        List<Map<String, Object>> stats = dbTypeCategoryService.getConnectionStatsByType();
        return ResponseEntity.ok(ApiResponse.success(stats, "DB 타입별 연결 통계를 조회했습니다."));
    }

    /**
     * GET /api/db-type-categories/{typeCode}
     * 특정 DB 타입 카테고리 조회
     */
    @GetMapping("/{typeCode}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCategoryByTypeCode(
            @PathVariable String typeCode) {
        Map<String, Object> category = dbTypeCategoryService.getCategoryByTypeCode(typeCode);
        if (category == null) {
            return ResponseEntity.status(404)
                    .body(ApiResponse.error("해당 DB 타입 카테고리를 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(category, "DB 타입 카테고리를 조회했습니다."));
    }

    /**
     * POST /api/db-type-categories
     * DB 타입 카테고리 생성
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> createCategory(
            @RequestBody Map<String, Object> body) {
        String typeCode = (String) body.get("type_code");
        String displayName = (String) body.get("display_name");

        if (typeCode == null || typeCode.isBlank() || displayName == null || displayName.isBlank()) {
            return ResponseEntity.status(400)
                    .body(ApiResponse.error("DB 타입 코드와 표시명은 필수입니다."));
        }

        try {
            Map<String, Object> created = dbTypeCategoryService.createCategory(body);
            return ResponseEntity.status(201).body(ApiResponse.success(created, "DB 타입 카테고리가 생성되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * POST /api/db-type-categories/initialize
     * 기본 DB 타입 카테고리 초기화
     * NOTE: POST /{typeCode} 충돌 없음 — 경로가 완전히 다름
     */
    @PostMapping("/initialize")
    public ResponseEntity<ApiResponse<Void>> initializeDefaultCategories() {
        dbTypeCategoryService.initializeDefaultCategories();
        return ResponseEntity.ok(ApiResponse.success(null, "기본 DB 타입 카테고리가 초기화되었습니다."));
    }

    /**
     * PUT /api/db-type-categories/{typeCode}
     * DB 타입 카테고리 수정
     */
    @PutMapping("/{typeCode}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateCategory(
            @PathVariable String typeCode,
            @RequestBody Map<String, Object> body) {
        Map<String, Object> updated = dbTypeCategoryService.updateCategory(typeCode, body);
        return ResponseEntity.ok(ApiResponse.success(updated, "DB 타입 카테고리가 수정되었습니다."));
    }

    /**
     * DELETE /api/db-type-categories/{typeCode}
     * DB 타입 카테고리 삭제 (비활성화)
     */
    @DeleteMapping("/{typeCode}")
    public ResponseEntity<ApiResponse<Void>> deleteCategory(
            @PathVariable String typeCode) {
        try {
            dbTypeCategoryService.deleteCategory(typeCode);
            return ResponseEntity.ok(ApiResponse.success(null, "DB 타입 카테고리가 삭제되었습니다."));
        } catch (IllegalStateException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }
}
