package com.erp.controller;

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

@RestController
@RequestMapping("/api/bom")
@RequiredArgsConstructor
@Slf4j
public class BomController {

    private final BomService bomService;

    // ─── 기본 CRUD ───

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

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getBomInfo(
            @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(bomService.getBomInfo(params)));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertBom(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(bomService.insertBom(body)));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateBom(
            @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(bomService.updateBom(body)));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteBom(
            @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(bomService.deleteBom(params)));
    }

    // ─── BOM 헤더 ───

    @GetMapping("/{bomId}/header")
    public ResponseEntity<ApiResponse<Object>> getBomHeader(@PathVariable String bomId) {
        Map<String, Object> data = bomService.getBomHeader(bomId);
        if (data == null) {
            return ResponseEntity.ok(ApiResponse.error("BOM을 찾을 수 없습니다"));
        }
        return ResponseEntity.ok(ApiResponse.success(data));
    }

    // ─── 이력 ───

    @GetMapping("/{bomId}/history")
    public ResponseEntity<ApiResponse<Object>> getBomHistory(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String bomId) {
        return ResponseEntity.ok(ApiResponse.success(bomService.getBomHistory(bomId, companyCode)));
    }

    @PostMapping("/{bomId}/history")
    public ResponseEntity<ApiResponse<Object>> addBomHistory(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable String bomId,
            @RequestBody Map<String, Object> body) {
        if (body.get("change_type") == null) {
            return ResponseEntity.ok(ApiResponse.error("change_type은 필수입니다"));
        }
        body.put("changed_by", userId);
        return ResponseEntity.ok(ApiResponse.success(bomService.addBomHistory(bomId, companyCode, body)));
    }

    // ─── 버전 ───

    @GetMapping("/{bomId}/versions")
    public ResponseEntity<ApiResponse<Object>> getBomVersions(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String bomId) {
        return ResponseEntity.ok(ApiResponse.success(bomService.getBomVersions(bomId, companyCode)));
    }

    @PostMapping("/{bomId}/versions")
    public ResponseEntity<ApiResponse<Object>> createBomVersion(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable String bomId,
            @RequestBody(required = false) Map<String, Object> body) {
        String versionName = body != null && body.get("version_name") != null ? String.valueOf(body.get("version_name")) : null;
        return ResponseEntity.ok(ApiResponse.success(bomService.createBomVersion(bomId, companyCode, userId, versionName)));
    }

    @PostMapping("/{bomId}/initialize-version")
    public ResponseEntity<ApiResponse<Object>> initializeBomVersion(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable String bomId) {
        return ResponseEntity.ok(ApiResponse.success(bomService.initializeBomVersion(bomId, companyCode, userId)));
    }

    @PostMapping("/{bomId}/versions/{versionId}/load")
    public ResponseEntity<ApiResponse<Object>> loadBomVersion(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String bomId,
            @PathVariable String versionId) {
        return ResponseEntity.ok(ApiResponse.success(bomService.loadBomVersion(bomId, versionId, companyCode)));
    }

    @PostMapping("/{bomId}/versions/{versionId}/activate")
    public ResponseEntity<ApiResponse<Object>> activateBomVersion(
            @PathVariable String bomId,
            @PathVariable String versionId) {
        return ResponseEntity.ok(ApiResponse.success(bomService.activateBomVersion(bomId, versionId)));
    }

    @DeleteMapping("/{bomId}/versions/{versionId}")
    public ResponseEntity<ApiResponse<Object>> deleteBomVersion(
            @PathVariable String bomId,
            @PathVariable String versionId) {
        boolean deleted = bomService.deleteBomVersion(bomId, versionId);
        if (!deleted) {
            return ResponseEntity.ok(ApiResponse.error("버전을 찾을 수 없습니다"));
        }
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    // ─── 엑셀 업로드/다운로드 ───

    @PostMapping("/excel-upload")
    @SuppressWarnings("unchecked")
    public ResponseEntity<ApiResponse<Object>> createBomFromExcel(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        List<Map<String, Object>> rows = (List<Map<String, Object>>) body.get("rows");
        if (rows == null || rows.isEmpty()) {
            return ResponseEntity.ok(ApiResponse.error("업로드할 데이터가 없습니다"));
        }
        Map<String, Object> result = bomService.createBomFromExcel(companyCode, userId, rows);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @PostMapping("/{bomId}/excel-upload-version")
    @SuppressWarnings("unchecked")
    public ResponseEntity<ApiResponse<Object>> createBomVersionFromExcel(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable String bomId,
            @RequestBody Map<String, Object> body) {
        List<Map<String, Object>> rows = (List<Map<String, Object>>) body.get("rows");
        if (rows == null || rows.isEmpty()) {
            return ResponseEntity.ok(ApiResponse.error("업로드할 데이터가 없습니다"));
        }
        String versionName = body.get("version_name") != null ? String.valueOf(body.get("version_name")) : null;
        Map<String, Object> result = bomService.createBomVersionFromExcel(bomId, companyCode, userId, rows, versionName);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @GetMapping("/{bomId}/excel-download")
    public ResponseEntity<ApiResponse<Object>> downloadBomExcelData(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String bomId) {
        return ResponseEntity.ok(ApiResponse.success(bomService.downloadBomExcelData(bomId, companyCode)));
    }
}
