package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ProductionService;
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;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/production")
@RequiredArgsConstructor
@Slf4j
public class ProductionController {

    private final ProductionService productionService;

    @GetMapping("/order-summary")
    public ResponseEntity<ApiResponse<Object>> getOrderSummary(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(productionService.getOrderSummary(params)));
    }

    @GetMapping("/stock-shortage")
    public ResponseEntity<ApiResponse<Object>> getStockShortage(
            @RequestAttribute("company_code") String companyCode) {
        return ResponseEntity.ok(ApiResponse.success(productionService.getStockShortage(companyCode)));
    }

    @GetMapping("/plan/{id}")
    public ResponseEntity<ApiResponse<Object>> getPlanById(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        return ResponseEntity.ok(ApiResponse.success(productionService.getPlanById(companyCode, id)));
    }

    @PutMapping("/plan/{id}")
    public ResponseEntity<ApiResponse<Object>> updatePlan(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable Long id,
            @RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(ApiResponse.success(productionService.updatePlan(companyCode, id, body, userId)));
    }

    @DeleteMapping("/plan/{id}")
    public ResponseEntity<ApiResponse<Object>> deletePlan(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        return ResponseEntity.ok(ApiResponse.success(productionService.deletePlan(companyCode, id)));
    }

    @PostMapping("/generate-schedule/preview")
    @SuppressWarnings("unchecked")
    public ResponseEntity<ApiResponse<Object>> previewSchedule(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        List<Map<String, Object>> items = (List<Map<String, Object>>) body.get("items");
        return ResponseEntity.ok(ApiResponse.success(productionService.previewSchedule(companyCode, items, body)));
    }

    @PostMapping("/generate-schedule")
    @SuppressWarnings("unchecked")
    public ResponseEntity<ApiResponse<Object>> generateSchedule(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        List<Map<String, Object>> items = (List<Map<String, Object>>) body.get("items");
        return ResponseEntity.ok(ApiResponse.success(productionService.generateSchedule(companyCode, items, body, userId)));
    }

    @PostMapping("/merge-schedules")
    @SuppressWarnings("unchecked")
    public ResponseEntity<ApiResponse<Object>> mergeSchedules(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        List<Number> rawIds = (List<Number>) body.get("schedule_ids");
        List<Long> scheduleIds = rawIds.stream().map(Number::longValue).collect(Collectors.toList());
        String productType = body.get("product_type") != null ? String.valueOf(body.get("product_type")) : "완제품";
        return ResponseEntity.ok(ApiResponse.success(productionService.mergeSchedules(companyCode, scheduleIds, productType, userId)));
    }

    @PostMapping("/generate-semi-schedule/preview")
    @SuppressWarnings("unchecked")
    public ResponseEntity<ApiResponse<Object>> previewSemiSchedule(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        List<Number> rawIds = (List<Number>) body.get("plan_ids");
        List<Long> planIds = rawIds.stream().map(Number::longValue).collect(Collectors.toList());
        return ResponseEntity.ok(ApiResponse.success(productionService.previewSemiSchedule(companyCode, planIds, body)));
    }

    @PostMapping("/generate-semi-schedule")
    @SuppressWarnings("unchecked")
    public ResponseEntity<ApiResponse<Object>> generateSemiSchedule(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        List<Number> rawIds = (List<Number>) body.get("plan_ids");
        List<Long> planIds = rawIds.stream().map(Number::longValue).collect(Collectors.toList());
        return ResponseEntity.ok(ApiResponse.success(productionService.generateSemiSchedule(companyCode, planIds, body, userId)));
    }

    @PostMapping("/plan/{id}/split")
    public ResponseEntity<ApiResponse<Object>> splitSchedule(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable Long id,
            @RequestBody Map<String, Object> body) {
        double splitQty = toDouble(body.get("split_qty"));
        return ResponseEntity.ok(ApiResponse.success(productionService.splitSchedule(companyCode, id, splitQty, userId)));
    }

    private double toDouble(Object val) {
        if (val == null) return 0.0;
        if (val instanceof Number) return ((Number) val).doubleValue();
        try { return Double.parseDouble(val.toString()); } catch (Exception e) { return 0.0; }
    }
}
