package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ComponentStandardService;
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;

/**
 * Component Standard 컨트롤러
 *
 * Node.js componentStandardRoutes.ts 포팅.
 *
 * GET    /api/component-standard                          — 목록 조회
 * GET    /api/component-standard/categories              — 카테고리 목록
 * GET    /api/component-standard/statistics              — 통계
 * GET    /api/component-standard/check-duplicate/{code} — 코드 중복 체크
 * GET    /api/component-standard/{component_code}        — 단건 조회
 * POST   /api/component-standard                        — 생성
 * PUT    /api/component-standard/{component_code}        — 수정
 * DELETE /api/component-standard/{component_code}        — 삭제
 * PUT    /api/component-standard/sort/order             — 정렬 순서 업데이트
 * POST   /api/component-standard/duplicate              — 복제
 */
@RestController
@RequestMapping("/api/component-standard")
@RequiredArgsConstructor
@Slf4j
public class ComponentStandardController {

    private final ComponentStandardService service;

    // ─────────────────────────────────────────────────────────
    // GET / — 목록 조회
    // ─────────────────────────────────────────────────────────

    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getComponents(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(service.getComponents(params)));
    }

    // ─────────────────────────────────────────────────────────
    // GET /categories — 카테고리 목록 (반드시 /{code} 앞에 선언)
    // ─────────────────────────────────────────────────────────

    @GetMapping("/categories")
    public ResponseEntity<ApiResponse<List<String>>> getCategories(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(service.getCategories(params)));
    }

    // ─────────────────────────────────────────────────────────
    // GET /statistics — 통계
    // ─────────────────────────────────────────────────────────

    @GetMapping("/statistics")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getStatistics(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(service.getStatistics(params)));
    }

    // ─────────────────────────────────────────────────────────
    // GET /check-duplicate/{component_code} — 중복 체크
    // ─────────────────────────────────────────────────────────

    @GetMapping("/check-duplicate/{component_code}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> checkDuplicate(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable("component_code") String componentCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("component_code", componentCode);
        params.put("company_code",    companyCode);
        boolean exists = service.checkDuplicate(params);
        return ResponseEntity.ok(ApiResponse.success(Map.of("exists", exists)));
    }

    // ─────────────────────────────────────────────────────────
    // GET /{component_code} — 단건 조회
    // ─────────────────────────────────────────────────────────

    @GetMapping("/{component_code}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getComponent(
            @PathVariable("component_code") String componentCode) {
        try {
            return ResponseEntity.ok(ApiResponse.success(service.getComponent(componentCode)));
        } catch (RuntimeException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        }
    }

    // ─────────────────────────────────────────────────────────
    // POST / — 생성
    // ─────────────────────────────────────────────────────────

    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> createComponent(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code",   companyCode);
        body.putIfAbsent("company_code", companyCode);
        try {
            return ResponseEntity.ok(ApiResponse.success(service.createComponent(body)));
        } catch (RuntimeException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    // ─────────────────────────────────────────────────────────
    // PUT /sort/order — 정렬 순서 업데이트 (/{code} 보다 먼저 선언)
    // ─────────────────────────────────────────────────────────

    @PutMapping("/sort/order")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateSortOrder(
            @RequestBody Map<String, Object> body) {
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> updates = (List<Map<String, Object>>) body.get("updates");
        if (updates == null || updates.isEmpty()) {
            return ResponseEntity.status(400).body(ApiResponse.error("updates 항목이 필요합니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(service.updateSortOrder(updates)));
    }

    // ─────────────────────────────────────────────────────────
    // PUT /{component_code} — 수정
    // ─────────────────────────────────────────────────────────

    @PutMapping("/{component_code}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateComponent(
            @PathVariable("component_code") String componentCode,
            @RequestBody Map<String, Object> body) {
        try {
            return ResponseEntity.ok(ApiResponse.success(service.updateComponent(componentCode, body)));
        } catch (RuntimeException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        }
    }

    // ─────────────────────────────────────────────────────────
    // DELETE /{component_code} — 삭제
    // ─────────────────────────────────────────────────────────

    @DeleteMapping("/{component_code}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteComponent(
            @PathVariable("component_code") String componentCode) {
        try {
            return ResponseEntity.ok(ApiResponse.success(service.deleteComponent(componentCode)));
        } catch (RuntimeException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        }
    }

    // ─────────────────────────────────────────────────────────
    // POST /duplicate — 복제
    // ─────────────────────────────────────────────────────────

    @PostMapping("/duplicate")
    public ResponseEntity<ApiResponse<Map<String, Object>>> duplicateComponent(
            @RequestBody Map<String, Object> body) {
        String sourceCode = str(body.get("source_code"));
        String newCode    = str(body.get("new_code"));
        String newName    = str(body.get("new_name"));

        if (sourceCode.isEmpty() || newCode.isEmpty() || newName.isEmpty()) {
            return ResponseEntity.status(400)
                    .body(ApiResponse.error("source_code, new_code, new_name 항목이 필요합니다."));
        }
        try {
            return ResponseEntity.ok(ApiResponse.success(
                    service.duplicateComponent(sourceCode, newCode, newName)));
        } catch (RuntimeException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    private String str(Object o) { return o == null ? "" : o.toString(); }
}
