package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.MultiConnectionService;
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/multi-connection")
@RequiredArgsConstructor
@Slf4j
public class MultiConnectionController {

    private final MultiConnectionService multiConnectionService;

    /** GET /connections/:connectionId/tables */
    @GetMapping("/connections/{connectionId}/tables")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTablesFromConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int connectionId) {
        List<Map<String, Object>> tables = multiConnectionService.getTablesFromConnection(connectionId);
        return ResponseEntity.ok(ApiResponse.success(tables,
                "커넥션 " + connectionId + "의 테이블 목록을 조회했습니다."));
    }

    /** GET /connections/:connectionId/tables/batch */
    @GetMapping("/connections/{connectionId}/tables/batch")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getBatchTablesWithColumns(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int connectionId) {
        List<Map<String, Object>> tables = multiConnectionService.getBatchTablesWithColumns(connectionId);
        return ResponseEntity.ok(ApiResponse.success(tables,
                "커넥션 " + connectionId + "의 테이블 정보를 배치 조회했습니다."));
    }

    /** GET /connections/:connectionId/tables/:tableName/columns */
    @GetMapping("/connections/{connectionId}/tables/{tableName}/columns")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getColumnsFromConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int connectionId,
            @PathVariable String tableName) {
        if (tableName == null || tableName.isBlank()) {
            return ResponseEntity.badRequest().body(ApiResponse.error("테이블명이 입력되지 않았습니다."));
        }
        List<Map<String, Object>> columns = multiConnectionService.getColumnsFromConnection(connectionId, tableName);
        return ResponseEntity.ok(ApiResponse.success(columns,
                "테이블 " + tableName + "의 컬럼 정보를 조회했습니다."));
    }

    /** POST /connections/:connectionId/query */
    @PostMapping("/connections/{connectionId}/query")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> fetchDataFromConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int connectionId,
            @RequestBody Map<String, Object> body) {
        if (body.get("table_name") == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("테이블명이 입력되지 않았습니다."));
        }
        List<Map<String, Object>> data = multiConnectionService.fetchDataFromConnection(connectionId, body);
        return ResponseEntity.ok(ApiResponse.success(data,
                "데이터 조회가 완료되었습니다. (" + data.size() + "건)"));
    }

    /** POST /connections/:connectionId/insert */
    @PostMapping("/connections/{connectionId}/insert")
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertDataToConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int connectionId,
            @RequestBody Map<String, Object> body) {
        if (body.get("table_name") == null || body.get("data") == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("테이블명과 데이터가 필요합니다."));
        }
        Map<String, Object> result = multiConnectionService.insertDataToConnection(connectionId, body);
        return ResponseEntity.status(201).body(ApiResponse.success(result, "데이터 삽입이 완료되었습니다."));
    }

    /** PUT /connections/:connectionId/update */
    @PutMapping("/connections/{connectionId}/update")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> updateDataToConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int connectionId,
            @RequestBody Map<String, Object> body) {
        if (body.get("table_name") == null || body.get("data") == null || body.get("conditions") == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("테이블명, 데이터, 조건이 모두 필요합니다."));
        }
        List<Map<String, Object>> result = multiConnectionService.updateDataToConnection(connectionId, body);
        return ResponseEntity.ok(ApiResponse.success(result,
                "데이터 업데이트가 완료되었습니다. (" + result.size() + "건)"));
    }

    /** DELETE /connections/:connectionId/delete */
    @DeleteMapping("/connections/{connectionId}/delete")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> deleteDataFromConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int connectionId,
            @RequestBody Map<String, Object> body) {
        if (body.get("table_name") == null || body.get("conditions") == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("테이블명과 삭제 조건이 필요합니다."));
        }
        List<Map<String, Object>> result = multiConnectionService.deleteDataFromConnection(connectionId, body);
        return ResponseEntity.ok(ApiResponse.success(result,
                "데이터 삭제가 완료되었습니다. (" + result.size() + "건)"));
    }

    /** POST /validate-self-operation */
    @PostMapping("/validate-self-operation")
    public ResponseEntity<ApiResponse<Map<String, Object>>> validateSelfOperation(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        if (body.get("table_name") == null || body.get("operation") == null || body.get("conditions") == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("테이블명, 작업 타입, 조건이 모두 필요합니다."));
        }
        String op = body.get("operation").toString();
        if (!op.equals("update") && !op.equals("delete")) {
            return ResponseEntity.badRequest().body(ApiResponse.error("작업 타입은 'update' 또는 'delete'만 허용됩니다."));
        }
        Map<String, Object> result = multiConnectionService.validateSelfOperation(body);
        return ResponseEntity.ok(ApiResponse.success(result, "검증이 완료되었습니다."));
    }
}
