package com.erp.controller;

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

/**
 * 테이블 이력 조회 컨트롤러
 * Node: tableHistoryRoutes.ts + tableHistoryController.ts
 */
@RestController
@RequestMapping("/api/table-history")
@RequiredArgsConstructor
@Slf4j
public class TableHistoryController {

    private final TableHistoryService tableHistoryService;

    /**
     * GET /api/table-history/{tableName}/check
     * 이력 테이블 존재 여부 확인
     */
    @GetMapping("/{tableName}/check")
    public ResponseEntity<ApiResponse<Map<String, Object>>> checkHistoryTableExists(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName) {

        Map<String, Object> params = new HashMap<>();
        params.put("table_name",   tableName);
        params.put("company_code", companyCode);

        Map<String, Object> data    = tableHistoryService.checkHistoryTableExists(params);
        String              message = (String) data.remove("_message");
        return ResponseEntity.ok(ApiResponse.success(data, message));
    }

    /**
     * GET /api/table-history/{tableName}/summary
     * 테이블 전체 이력 요약 (operation_type별 집계)
     */
    @GetMapping("/{tableName}/summary")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTableHistorySummary(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName) {

        Map<String, Object> params = new HashMap<>();
        params.put("table_name",   tableName);
        params.put("company_code", companyCode);

        try {
            List<Map<String, Object>> data = tableHistoryService.getTableHistorySummary(params);
            return ResponseEntity.ok(ApiResponse.success(data, "이력 요약 조회 성공"));
        } catch (RuntimeException e) {
            if ("TABLE_NOT_FOUND".equals(e.getMessage())) {
                return ResponseEntity.status(404).body(ApiResponse.error("이력 테이블이 존재하지 않습니다."));
            }
            throw e;
        }
    }

    /**
     * GET /api/table-history/{tableName}/all
     * 전체 테이블 이력 조회 (레코드 ID 없이)
     */
    @GetMapping("/{tableName}/all")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAllTableHistory(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @RequestParam Map<String, Object> queryParams) {

        queryParams.put("table_name",   tableName);
        queryParams.put("company_code", companyCode);

        try {
            Map<String, Object> data = tableHistoryService.getAllTableHistory(queryParams);
            return ResponseEntity.ok(ApiResponse.success(data, "전체 테이블 이력 조회 성공"));
        } catch (RuntimeException e) {
            if ("TABLE_NOT_FOUND".equals(e.getMessage())) {
                return ResponseEntity.status(404).body(ApiResponse.error("이력 테이블이 존재하지 않습니다."));
            }
            throw e;
        }
    }

    /**
     * GET /api/table-history/{tableName}/{recordId}/timeline
     * 특정 레코드 변경 타임라인 조회 (동일 시간대 그룹화)
     */
    @GetMapping("/{tableName}/{recordId}/timeline")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getRecordTimeline(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @PathVariable String recordId) {

        Map<String, Object> params = new HashMap<>();
        params.put("table_name",   tableName);
        params.put("record_id",    recordId);
        params.put("company_code", companyCode);

        try {
            List<Map<String, Object>> data = tableHistoryService.getRecordTimeline(params);
            return ResponseEntity.ok(ApiResponse.success(data, "타임라인 조회 성공"));
        } catch (RuntimeException e) {
            if ("TABLE_NOT_FOUND".equals(e.getMessage())) {
                return ResponseEntity.status(404).body(ApiResponse.error("이력 테이블이 존재하지 않습니다."));
            }
            throw e;
        }
    }

    /**
     * GET /api/table-history/{tableName}/{recordId}
     * 특정 레코드 변경 이력 상세 조회
     */
    @GetMapping("/{tableName}/{recordId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getRecordHistory(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @PathVariable String recordId,
            @RequestParam Map<String, Object> queryParams) {

        queryParams.put("table_name",   tableName);
        queryParams.put("record_id",    recordId);
        queryParams.put("company_code", companyCode);

        try {
            Map<String, Object> data = tableHistoryService.getRecordHistory(queryParams);
            return ResponseEntity.ok(ApiResponse.success(data, "이력 조회 성공"));
        } catch (RuntimeException e) {
            if ("TABLE_NOT_FOUND".equals(e.getMessage())) {
                return ResponseEntity.status(404).body(ApiResponse.error(
                        "이력 테이블이 존재하지 않습니다. 테이블 타입 관리에서 이력 관리를 활성화해주세요."));
            }
            throw e;
        }
    }
}
