package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.BatchManagementService;
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/batch-management")
@RequiredArgsConstructor
@Slf4j
public class BatchManagementController {

    private final BatchManagementService batchManagementService;

    // ── Dashboard Stats ───────────────────────────────────────────────────────

    /** GET /api/batch-management/stats — 배치 대시보드 통계 */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getBatchStats(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(batchManagementService.getBatchStats(params)));
    }

    // ── Node Flows ────────────────────────────────────────────────────────────

    /** GET /api/batch-management/node-flows — 배치 설정에서 노드 플로우 선택용 목록 */
    @GetMapping("/node-flows")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getNodeFlows(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(batchManagementService.getNodeFlows(params)));
    }

    // ── Connections ───────────────────────────────────────────────────────────

    /** GET /api/batch-management/connections — 사용 가능한 커넥션 목록 조회 */
    @GetMapping("/connections")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getAvailableConnections(
            @RequestAttribute("company_code") String companyCode) {
        return ResponseEntity.ok(ApiResponse.success(
                batchManagementService.getAvailableConnections(companyCode)));
    }

    /** GET /api/batch-management/connections/:type/tables — 내부 DB 테이블 목록 */
    @GetMapping("/connections/{type}/tables")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTablesFromConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String type) {
        return ResponseEntity.ok(ApiResponse.success(
                batchManagementService.getTablesFromConnection(type, null, companyCode)));
    }

    /** GET /api/batch-management/connections/:type/:id/tables — 외부 DB 테이블 목록 */
    @GetMapping("/connections/{type}/{id}/tables")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTablesFromExternalConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String type,
            @PathVariable Long id) {
        return ResponseEntity.ok(ApiResponse.success(
                batchManagementService.getTablesFromConnection(type, id, companyCode)));
    }

    /** GET /api/batch-management/connections/:type/tables/:tableName/columns — 내부 DB 컬럼 정보 */
    @GetMapping("/connections/{type}/tables/{tableName}/columns")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTableColumns(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String type,
            @PathVariable String tableName) {
        return ResponseEntity.ok(ApiResponse.success(
                batchManagementService.getTableColumns(type, null, tableName, companyCode)));
    }

    /** GET /api/batch-management/connections/:type/:id/tables/:tableName/columns — 외부 DB 컬럼 정보 */
    @GetMapping("/connections/{type}/{id}/tables/{tableName}/columns")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getExternalTableColumns(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String type,
            @PathVariable Long id,
            @PathVariable String tableName) {
        return ResponseEntity.ok(ApiResponse.success(
                batchManagementService.getTableColumns(type, id, tableName, companyCode)));
    }

    // ── Batch Configs ─────────────────────────────────────────────────────────

    /** POST /api/batch-management/batch-configs — 배치 설정 생성 */
    @PostMapping("/batch-configs")
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertBatchConfig(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        Map<String, Object> result = batchManagementService.insertBatchConfig(body);
        return ResponseEntity.status(201).body(ApiResponse.success(result, "배치 설정이 성공적으로 생성되었습니다."));
    }

    /** GET /api/batch-management/batch-configs — 배치 설정 목록 조회 */
    @GetMapping("/batch-configs")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getBatchConfigList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(batchManagementService.getBatchConfigList(params)));
    }

    /** GET /api/batch-management/batch-configs/:id — 특정 배치 설정 조회 */
    @GetMapping("/batch-configs/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getBatchConfigInfo(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("id", id);
        Map<String, Object> result = batchManagementService.getBatchConfigInfo(params);
        if (result == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("배치 설정을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /** GET /api/batch-management/batch-configs/:id/sparkline — 최근 24시간 1시간 단위 실행 집계 */
    @GetMapping("/batch-configs/{id}/sparkline")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getBatchSparkline(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("batch_config_id", id);
        return ResponseEntity.ok(ApiResponse.success(batchManagementService.getBatchSparkline(params)));
    }

    /** GET /api/batch-management/sparkline — 회사 전체 배치의 최근 24시간 1시간 단위 실행 집계 (24개 슬롯 고정) */
    @GetMapping("/sparkline")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getGlobalSparkline(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(batchManagementService.getGlobalSparkline(params)));
    }

    /** GET /api/batch-management/batch-configs/:id/recent-logs — 최근 실행 로그 (최대 20건) */
    @GetMapping("/batch-configs/{id}/recent-logs")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getBatchRecentLogs(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("batch_config_id", id);
        return ResponseEntity.ok(ApiResponse.success(batchManagementService.getBatchRecentLogs(params)));
    }

    /** PUT /api/batch-management/batch-configs/:id — 배치 설정 업데이트 */
    @PutMapping("/batch-configs/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateBatchConfig(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("id", id);
        return ResponseEntity.ok(ApiResponse.success(
                batchManagementService.updateBatchConfig(body), "배치 설정이 성공적으로 업데이트되었습니다."));
    }

    /** POST /api/batch-management/batch-configs/:id/execute — 배치 수동 실행 */
    @PostMapping("/batch-configs/{id}/execute")
    public ResponseEntity<ApiResponse<Map<String, Object>>> executeBatchConfig(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("id", id);
        return ResponseEntity.ok(ApiResponse.success(
                batchManagementService.executeBatchConfig(params), "배치가 성공적으로 실행되었습니다."));
    }

    // ── REST API ──────────────────────────────────────────────────────────────

    /** POST /api/batch-management/rest-api/preview — REST API 데이터 미리보기 */
    @PostMapping("/rest-api/preview")
    public ResponseEntity<ApiResponse<Map<String, Object>>> previewRestApiData(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(batchManagementService.previewRestApiData(body)));
    }

    /** POST /api/batch-management/rest-api/save — REST API 배치 저장 */
    @PostMapping("/rest-api/save")
    public ResponseEntity<ApiResponse<Map<String, Object>>> saveRestApiBatch(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(
                batchManagementService.saveRestApiBatch(body), "REST API 배치가 성공적으로 저장되었습니다."));
    }

    // ── Auth Services ─────────────────────────────────────────────────────────

    /** GET /api/batch-management/auth-services — 인증 토큰 서비스명 목록 조회 */
    @GetMapping("/auth-services")
    public ResponseEntity<ApiResponse<List<String>>> getAuthServiceNames(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(batchManagementService.getAuthServiceNames(params)));
    }
}
