package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.DeliveryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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/delivery")
@Slf4j
public class DeliveryController {

    @Autowired private DeliveryService deliveryService;

    @GetMapping("/status")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDeliveryStatus(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(deliveryService.getDeliveryStatus(params)));
    }

    @GetMapping("/delayed")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getDelayedDeliveries(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(deliveryService.getDelayedDeliveries(params)));
    }

    @GetMapping("/issues")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getCustomerIssues(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam(required = false) String status) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        if (status != null) params.put("status", status);
        return ResponseEntity.ok(ApiResponse.success(deliveryService.getCustomerIssues(params)));
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Void>> updateDeliveryStatus(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String id,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("id", id);
        deliveryService.updateDeliveryStatus(body);
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    @PutMapping("/issues/{id}/status")
    public ResponseEntity<ApiResponse<Void>> updateIssueStatus(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String id,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("id", id);
        deliveryService.updateIssueStatus(body);
        return ResponseEntity.ok(ApiResponse.success(null));
    }
}
