package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.MoldService;
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/mold")
@RequiredArgsConstructor
@Slf4j
public class MoldController {

    private final MoldService moldService;

    // ── 금형 마스터 ───────────────────────────────────────────────────────────

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

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

    @GetMapping("/{moldCode}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getMoldDetail(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String moldCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("mold_code", moldCode);
        Map<String, Object> result = moldService.getMoldInfo(params);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("금형을 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> createMold(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("writer", userId);
        if (body.get("mold_code") == null || body.get("mold_name") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("금형코드와 금형명은 필수입니다."));
        }
        try {
            return ResponseEntity.ok(ApiResponse.success(moldService.insertMold(body), "금형이 등록되었습니다."));
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().contains("unique")) {
                return ResponseEntity.status(409).body(ApiResponse.error("이미 존재하는 금형코드입니다."));
            }
            return ResponseEntity.status(500).body(ApiResponse.error(e.getMessage()));
        }
    }

    @PutMapping("/{moldCode}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateMold(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String moldCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("mold_code", moldCode);
        Map<String, Object> result = moldService.updateMold(body);
        if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("금형을 찾을 수 없습니다."));
        return ResponseEntity.ok(ApiResponse.success(result, "금형이 수정되었습니다."));
    }

    @DeleteMapping("/{moldCode}")
    public ResponseEntity<ApiResponse<Void>> deleteMold(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String moldCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("mold_code", moldCode);
        if (!moldService.deleteMold(params)) {
            return ResponseEntity.status(404).body(ApiResponse.error("금형을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "금형이 삭제되었습니다."));
    }

    // ── 일련번호 ──────────────────────────────────────────────────────────────

    @GetMapping("/{moldCode}/serials")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getMoldSerials(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String moldCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("mold_code", moldCode);
        return ResponseEntity.ok(ApiResponse.success(moldService.getMoldSerialList(params)));
    }

    @PostMapping("/{moldCode}/serials")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createMoldSerial(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable String moldCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("mold_code", moldCode);
        body.put("writer", userId);
        try {
            return ResponseEntity.ok(ApiResponse.success(moldService.insertMoldSerial(body), "일련번호가 등록되었습니다."));
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().contains("unique")) {
                return ResponseEntity.status(409).body(ApiResponse.error("이미 존재하는 일련번호입니다."));
            }
            return ResponseEntity.status(500).body(ApiResponse.error(e.getMessage()));
        }
    }

    @DeleteMapping("/serials/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteMoldSerial(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("id", id);
        if (!moldService.deleteMoldSerial(params)) {
            return ResponseEntity.status(404).body(ApiResponse.error("일련번호를 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "일련번호가 삭제되었습니다."));
    }

    @GetMapping("/{moldCode}/serial-summary")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getMoldSerialSummary(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String moldCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("mold_code", moldCode);
        return ResponseEntity.ok(ApiResponse.success(moldService.getMoldSerialSummary(params)));
    }

    // ── 점검항목 ──────────────────────────────────────────────────────────────

    @GetMapping("/{moldCode}/inspections")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getMoldInspections(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String moldCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("mold_code", moldCode);
        return ResponseEntity.ok(ApiResponse.success(moldService.getMoldInspectionList(params)));
    }

    @PostMapping("/{moldCode}/inspections")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createMoldInspection(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable String moldCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("mold_code", moldCode);
        body.put("writer", userId);
        if (body.get("inspection_item") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("점검항목명은 필수입니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(moldService.insertMoldInspection(body), "점검항목이 등록되었습니다."));
    }

    @DeleteMapping("/inspections/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteMoldInspection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("id", id);
        if (!moldService.deleteMoldInspection(params)) {
            return ResponseEntity.status(404).body(ApiResponse.error("점검항목을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "점검항목이 삭제되었습니다."));
    }

    // ── 부품 ──────────────────────────────────────────────────────────────────

    @GetMapping("/{moldCode}/parts")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getMoldParts(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String moldCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("mold_code", moldCode);
        return ResponseEntity.ok(ApiResponse.success(moldService.getMoldPartList(params)));
    }

    @PostMapping("/{moldCode}/parts")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createMoldPart(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable String moldCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("mold_code", moldCode);
        body.put("writer", userId);
        if (body.get("part_name") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("부품명은 필수입니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(moldService.insertMoldPart(body), "부품이 등록되었습니다."));
    }

    @DeleteMapping("/parts/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteMoldPart(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("id", id);
        if (!moldService.deleteMoldPart(params)) {
            return ResponseEntity.status(404).body(ApiResponse.error("부품을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "부품이 삭제되었습니다."));
    }
}
