package services

import (
	"nearle/models"
	"nearle/repositories"
	"time"
)

type StockRequestService interface {
	CreateStockRequest(req *models.StockRequest) error
	GetStockRequests(tenantID int, locationID int, status string, date string, pageNo int, pageSize int) ([]models.StockRequest, error)
	UpdateStockRequest(requestID int, status string) error
}

type stockRequestService struct {
	repo           repositories.StockRequestRepository
	productService ProductService
}

func NewStockRequestService(repo repositories.StockRequestRepository, productService ProductService) StockRequestService {
	return &stockRequestService{repo: repo, productService: productService}
}

func (s *stockRequestService) CreateStockRequest(req *models.StockRequest) error {
	return s.repo.CreateStockRequest(req)
}

func (s *stockRequestService) GetStockRequests(tenantID int, locationID int, status string, date string, pageNo int, pageSize int) ([]models.StockRequest, error) {
	return s.repo.GetStockRequests(tenantID, locationID, status, date, pageNo, pageSize)
}

func (s *stockRequestService) UpdateStockRequest(requestID int, status string) error {
	// If the request is being marked as Received, we need to update the actual store inventory
	if status == "Received" {
		req, err := s.repo.GetStockRequestByID(requestID)
		if err != nil {
			return err
		}

		if req.Status != "Received" { // prevent double receiving
			stk := models.Productstock{
				Tenantid:   req.Tenantid,
				Locationid: req.Locationid,
				Productid:  req.Productid,
				Quantity:   req.Qty,
				Stocktype:  "in",
				Stockdate:  time.Now(),
			}

			err = s.productService.CreateProductStock([]models.Productstock{stk})
			if err != nil {
				return err
			}
		}
	}

	return s.repo.UpdateStockRequest(requestID, status)
}
