package controllers

import (
	"net/http"
	"strconv"

	"nearle/models"
	"nearle/services"

	"github.com/gofiber/fiber/v2"
)

type StockRequestController struct {
	stockRequestService services.StockRequestService
}

func NewStockRequestController(stockRequestService services.StockRequestService) *StockRequestController {
	return &StockRequestController{stockRequestService: stockRequestService}
}

func (ctl *StockRequestController) CreateStockRequest(c *fiber.Ctx) error {
	var input models.StockRequest
	if err := c.BodyParser(&input); err != nil {
		return c.JSON(fiber.Map{"code": http.StatusBadRequest, "message": "Invalid input", "status": false})
	}

	if input.Status == "" {
		input.Status = "Pending"
	}

	err := ctl.stockRequestService.CreateStockRequest(&input)
	if err != nil {
		return c.JSON(fiber.Map{"code": http.StatusInternalServerError, "message": err.Error(), "status": false})
	}

	return c.JSON(fiber.Map{"code": 200, "message": "Stock request created", "status": true, "details": input})
}

func (ctl *StockRequestController) GetStockRequests(c *fiber.Ctx) error {
	tenantID, _ := strconv.Atoi(c.Query("tenantid", "0"))
	locationID, _ := strconv.Atoi(c.Query("locationid", "0"))
	status := c.Query("status", "")
	date := c.Query("date", "")
	pageNo, _ := strconv.Atoi(c.Query("pageno", "1"))
	pageSize, _ := strconv.Atoi(c.Query("pagesize", "50"))

	data, err := ctl.stockRequestService.GetStockRequests(tenantID, locationID, status, date, pageNo, pageSize)
	if err != nil {
		return c.JSON(fiber.Map{"code": http.StatusInternalServerError, "message": err.Error(), "status": false})
	}

	return c.JSON(fiber.Map{"code": 200, "message": "Success", "status": true, "details": data})
}

func (ctl *StockRequestController) UpdateStockRequest(c *fiber.Ctx) error {
	var input struct {
		RequestID int    `json:"requestid"`
		Status    string `json:"status"`
	}
	if err := c.BodyParser(&input); err != nil {
		return c.JSON(fiber.Map{"code": http.StatusBadRequest, "message": "Invalid input", "status": false})
	}

	err := ctl.stockRequestService.UpdateStockRequest(input.RequestID, input.Status)
	if err != nil {
		return c.JSON(fiber.Map{"code": http.StatusInternalServerError, "message": err.Error(), "status": false})
	}

	return c.JSON(fiber.Map{"code": 200, "message": "Stock request updated", "status": true})
}
