package com.utopiaindustries.restcontroller;

import com.utopiaindustries.dao.ctp.CutPieceTypeDAO;
import com.utopiaindustries.dao.ctp.SkuCutPiecesDAO;
import com.utopiaindustries.model.ctp.CutPieceType;
import com.utopiaindustries.model.ctp.SkuCutPieces;
import com.utopiaindustries.service.JobCardService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping( "/rest/cut-pieces" )
public class CutPieceRestController {

    private final JobCardService jobCardService;
    private final SkuCutPiecesDAO skuCutPiecesDAO;
    private final CutPieceTypeDAO cutPieceTypeDAO;

    public CutPieceRestController(JobCardService jobCardService, SkuCutPiecesDAO skuCutPiecesDAO, CutPieceTypeDAO cutPieceTypeDAO) {
        this.jobCardService = jobCardService;
        this.skuCutPiecesDAO = skuCutPiecesDAO;
        this.cutPieceTypeDAO = cutPieceTypeDAO;
    }

    @GetMapping
    public List<CutPieceType> getBySku(@RequestParam("sku") String sku) {
        try {
            ArrayList<CutPieceType> cutPieceTypes = new ArrayList<>();
            List<SkuCutPieces> skuCutPieces =  skuCutPiecesDAO.findBySku(sku);
            for (SkuCutPieces skuCutPieces1 : skuCutPieces){
                CutPieceType cutPieceType = cutPieceTypeDAO.findByTitle(skuCutPieces1.getType());
                cutPieceTypes.add(cutPieceType);
            }
            return cutPieceTypes;
        } catch (Exception e) {
            throw new RuntimeException("An error occurred while fetching data for SKU: " + sku, e);
        }
    }

    @PostMapping
    public String deleteJobCardItemPiece( @RequestParam("cut-piece-id") long cutPieceId ){
        try {
            return jobCardService.deleteCutPieceItem( cutPieceId );
        } catch ( Exception e ){
            return e.getMessage();
        }
    }
}
