package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.BatchService;
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-configs")
@RequiredArgsConstructor
@Slf4j
public class BatchController {
    private final BatchService batchService;

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

    @GetMapping("/connections")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getConnections(
            @RequestAttribute("company_code") String companyCode) {
        return ResponseEntity.ok(ApiResponse.success(batchService.getConnections(companyCode)));
    }

    @GetMapping("/connections/{type}/tables")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTablesByType(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String type) {
        return ResponseEntity.ok(ApiResponse.success(batchService.getTables(type, null)));
    }

    @GetMapping("/connections/{type}/{connectionId}/tables")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTablesByTypeAndId(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String type,
            @PathVariable Long connectionId) {
        return ResponseEntity.ok(ApiResponse.success(batchService.getTables(type, connectionId)));
    }

    @GetMapping("/connections/{type}/tables/{tableName}/columns")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getColumnsByType(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String type,
            @PathVariable String tableName) {
        return ResponseEntity.ok(ApiResponse.success(batchService.getColumns(type, null, tableName)));
    }

    @GetMapping("/connections/{type}/{connectionId}/tables/{tableName}/columns")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getColumnsByTypeAndId(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String type,
            @PathVariable Long connectionId,
            @PathVariable String tableName) {
        return ResponseEntity.ok(ApiResponse.success(batchService.getColumns(type, connectionId, tableName)));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getBatchInfo(
            @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 = batchService.getBatchInfo(params);
        if (result == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("배치 설정을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertBatch(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("created_by", userId);
        body.put("updated_by", userId);

        // API 필드명(cron_expression) → DB 필드명(cron_schedule) 매핑
        if (body.containsKey("cron_expression") && !body.containsKey("cron_schedule")) {
            body.put("cron_schedule", body.get("cron_expression"));
        }

        Map<String, Object> created = batchService.insertBatch(body);
        return ResponseEntity.status(201).body(ApiResponse.success(created, "배치 설정이 성공적으로 생성되었습니다."));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateBatch(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable Long id,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("updated_by", userId);
        body.put("id", id);

        // API 필드명(cron_expression) → DB 필드명(cron_schedule) 매핑
        if (body.containsKey("cron_expression") && !body.containsKey("cron_schedule")) {
            body.put("cron_schedule", body.get("cron_expression"));
        }

        Map<String, Object> updated = batchService.updateBatch(body);
        return ResponseEntity.ok(ApiResponse.success(updated, "배치 설정이 성공적으로 수정되었습니다."));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteBatch(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("updated_by", userId);
        params.put("id", id);
        batchService.deleteBatch(params);
        return ResponseEntity.ok(ApiResponse.success(null, "배치 설정이 성공적으로 삭제되었습니다."));
    }
}
