/*
**************************************************************************************
* Program Name  : PurchaseOrderController.java
* Author        : Kawade Swapnali
* Date          : Feb 14, 2026
* System Name   : gswbs
* SRF No.       : 
* Purpose       : To expose REST APIs for Purchase Order module such as
*                 Fetch (single/all), Save (bulk), Update and Delete
*                 (single & bulk).
*
* Fields        : purchaseOrderId (PK),
*                 purchaseOrderNo,
*                 vendorName,
*                 vendorGSTNo,
*                 vendorAddress,
*                 requestedBy,
*                 purchaseOrderStatus,
*                 assetType,
*                 assetMake,
*                 assetModel,
*                 description,
*                 quantity,
*                 unitPrice,
*                 gstPercentage,
*                 gstAmount,
*                 subTotal,
*                 grandTotal,
*                 purchaseOrderCreateDate,
*                 deliveryLocation,
*                 expectedDate,
*                 loginId,
*                 status
*
* Functions     : getAllRecords(),
*                 getAllPurchaseOrderByLoginId(),
*                 saveAllRecords(),
*                 updateRecords(),
*                 deleteRecords(),
*                 deleteMultipalRecords()
*
* Called From   : Frontend (Angular UI / API Client)
* Beans Accessed: PurchaseOrderService, PurchaseOrder (Entity)
**************************************************************************************
*/
package com.coder.purchase.order.controller;

import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.coder.purchase.order.dto.ApiResponse;
import com.coder.purchase.order.dto.PurchaseOrderDTO;
import com.coder.purchase.order.model.PurchaseOrder;
import com.coder.purchase.order.model.SaveToPurchaseOrderResponse;
import com.coder.purchase.order.service.PurchaseOrderService;

import lombok.RequiredArgsConstructor;



@RequiredArgsConstructor
@RestController
@RequestMapping("/purchase_order_service")
public class PurchaseOrderController {

    @Autowired
    private  final PurchaseOrderService purchaseOrderService;
    
    /* FETCH THE SINGAL DESIGNATION BY DESIGNATION ID AND COMPANY ID */

    /* ================= FETCH SINGLE ================= */
    @GetMapping("/single/{prefix}/{year}/{code}")
    public ResponseEntity<?> getSinglePurchaseOrder(
            @PathVariable String prefix,
            @PathVariable String year,
            @PathVariable String code
    ) {
        try {
            String purchaseOrderId = prefix + "/" + year + "/" + code;

            PurchaseOrderDTO dto =
                    purchaseOrderService.getSinglePurchaseOrder(purchaseOrderId);

            return new ResponseEntity<>(dto, HttpStatus.OK);

        } catch (NoSuchElementException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);

        } catch (Exception e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
	
	/* FETCH ALL PURCHASE ORDER */
    @GetMapping("/fetch-all-purchase-order")
    public ResponseEntity<ApiResponse<List<PurchaseOrderDTO>>> fetchAllPurchaseOrders() {

        try {
            List<PurchaseOrderDTO> result =
                    purchaseOrderService.fetchAllPurchaseOrder();

            if (result == null || result.isEmpty()) {
                return ResponseEntity.ok(
                        ApiResponse.success("No purchase orders found", Collections.emptyList())
                );
            }

            return ResponseEntity.ok(
                    ApiResponse.success("Purchase orders fetched successfully", result)
            );

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("Failed to fetch purchase orders"));
        }
    }

	
	/* FETCH ALL DESIGNATION BY COMPANY ID */
//	@GetMapping("/getAllPurchaseOrderByCreatedBy/{prefix}/{year}/{code}")
//	public ResponseEntity<List<PurchaseOrder>> getAllPurchaseOrderByLoginId(
//			@PathVariable(name = "prefix") String prefix,
//			@PathVariable(name = "year") String year,
//			@PathVariable(name = "code") String code
//			){
//		try {
//			String loginId = prefix +"/"+ year +"/"+ code;
//			List<PurchaseOrder> result = purchaseOrderService.getAllPurchaseOrderByCreatedBy(loginId);
//			return new ResponseEntity<List<PurchaseOrder>>(result,HttpStatus.OK);
//		}
//		catch(NoSuchElementException e) {
//			return new ResponseEntity<List<PurchaseOrder>>(HttpStatus.NOT_FOUND);
//		}
//	}
//	
    @GetMapping("/getAllPurchaseOrderByLoginId/{loginId}")
    public ResponseEntity<ApiResponse<List<PurchaseOrderDTO>>> getAllByLoginId(
            @PathVariable String loginId
    ) {
        try {

            List<PurchaseOrderDTO> result =
                    purchaseOrderService.getAllPurchaseOrderByCreatedBy(loginId);

            if (result == null || result.isEmpty()) {
                return ResponseEntity.ok(
                        ApiResponse.success("No purchase orders found", Collections.emptyList())
                );
            }

            return ResponseEntity.ok(
                    ApiResponse.success("Purchase orders fetched successfully", result)
            );

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("Error fetching purchase orders"));
        }
    }
	
	/*
	 * SAVE MULTIPAL DESIGNATION AT ONE TIME AND CREATE A EACH DESIGNATION ID AUTOMATICALLY 
	 * BY DES,CURRENT YEAR AND NUMBER FOR EXAMPLE DES/2026/001
	 */
	@PostMapping("/saveAll")
	public ResponseEntity<SaveToPurchaseOrderResponse> saveAllRecords(@RequestBody List<PurchaseOrder> purchaseOrder) {
	    try {
	    	SaveToPurchaseOrderResponse result = purchaseOrderService.saveAllPurchaseOrder(purchaseOrder);
	        return ResponseEntity.ok(result);
	    } catch (NoSuchElementException e) {
	        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
	    } catch (Exception e) {
	        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	    }
	}
	
	/*
	 * UPDATE SINGAL DESIGNATION BY DESIGNATION ID AND COMPANY ID
	 */
	@PutMapping("/update/{prefix}/{year}/{code}")
	public ResponseEntity<?> updateRecords(
			@PathVariable(name = "prefix") String prefix,
			@PathVariable(name = "year") String year,
			@PathVariable(name = "code") String code, 
			@RequestBody PurchaseOrder purchaseOrder){
		try {
			String purchaseOrderId = prefix + "/" + year + "/" + code;
			PurchaseOrder purchaseOrderDb = purchaseOrderService.update(purchaseOrderId,purchaseOrder);
			return new ResponseEntity<PurchaseOrder>(purchaseOrderDb,HttpStatus.OK);
		}
		catch(NoSuchElementException e) {
			return new ResponseEntity<PurchaseOrder>(HttpStatus.NOT_FOUND);
		}
		catch (Exception e) {
		    return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
		}

	}
	
	/*
	 * DELETE MULTIPAL DESIGNATION AT ONE TIME BY oLIST OF DESIGNATION ID
	 */
	@PostMapping("/delete-multipal-purchaseOrder")
	public ResponseEntity<?> deleteMultipalRecords(@RequestBody List<String> purchaseOrderIds){
		try {
			boolean result = purchaseOrderService.multipalDelete(purchaseOrderIds);
			return new ResponseEntity<Boolean>(result,HttpStatus.OK);
		}catch(Exception e){
			return new ResponseEntity<String>(e.getMessage(),HttpStatus.BAD_REQUEST);
		}
	}
//	@PutMapping("/update-status/{prefix}/{year}/{code}")
//	public ResponseEntity<?> updateStatus(
//
//	        @PathVariable String prefix,
//
//	        @PathVariable String year,
//
//	        @PathVariable String code,
//
//	        @RequestParam String status) {
//
//	    try {
//
//	        String purchaseOrderId =
//	                prefix + "/" + year + "/" + code;
//
//	        PurchaseOrder po =
//	                purchaseOrderService
//	                .getById(purchaseOrderId);
//
//	        po.setPoStatus(status);
//
//	        purchaseOrderService.save(po);
//
//	        return ResponseEntity.ok(
//	                "Purchase Order Status Updated Successfully");
//
//	    } catch (Exception e) {
//
//	        return ResponseEntity
//	                .status(HttpStatus.INTERNAL_SERVER_ERROR)
//	                .body(e.getMessage());
//	    }
//	}
//	
}
