package mappers

import (
	"apskel-pos-be/internal/entities"
	"apskel-pos-be/internal/models"
	"github.com/google/uuid"
)

func InventoryEntityToModel(entity *entities.Inventory) *models.Inventory {
	if entity == nil {
		return nil
	}

	return &models.Inventory{
		ID:           entity.ID,
		OutletID:     entity.OutletID,
		ProductID:    entity.ProductID,
		Quantity:     entity.Quantity,
		ReorderLevel: entity.ReorderLevel,
		UpdatedAt:    entity.UpdatedAt,
	}
}

func InventoryModelToEntity(model *models.Inventory) *entities.Inventory {
	if model == nil {
		return nil
	}

	return &entities.Inventory{
		ID:           model.ID,
		OutletID:     model.OutletID,
		ProductID:    model.ProductID,
		Quantity:     model.Quantity,
		ReorderLevel: model.ReorderLevel,
		UpdatedAt:    model.UpdatedAt,
	}
}

func CreateInventoryRequestToEntity(req *models.CreateInventoryRequest) *entities.Inventory {
	if req == nil {
		return nil
	}

	return &entities.Inventory{
		OutletID:     req.OutletID,
		ProductID:    req.ProductID,
		Quantity:     req.Quantity,
		ReorderLevel: req.ReorderLevel,
	}
}

func InventoryEntityToResponse(entity *entities.Inventory) *models.InventoryResponse {
	if entity == nil {
		return nil
	}

	productName := ""
	if entity.Product.ID != uuid.Nil {
		productName = entity.Product.Name
	}

	return &models.InventoryResponse{
		ID:           entity.ID,
		OutletID:     entity.OutletID,
		ProductID:    entity.ProductID,
		ProductName:  productName,
		Quantity:     entity.Quantity,
		ReorderLevel: entity.ReorderLevel,
		IsLowStock:   entity.IsLowStock(),
		UpdatedAt:    entity.UpdatedAt,
	}
}

func UpdateInventoryEntityFromRequest(entity *entities.Inventory, req *models.UpdateInventoryRequest) {
	if entity == nil || req == nil {
		return
	}

	if req.Quantity != nil {
		entity.Quantity = *req.Quantity
	}

	if req.ReorderLevel != nil {
		entity.ReorderLevel = *req.ReorderLevel
	}
}

func InventoryAdjustmentRequestToModel(req *models.InventoryAdjustmentRequest) *models.InventoryAdjustmentRequest {
	if req == nil {
		return nil
	}

	return &models.InventoryAdjustmentRequest{
		Delta:  req.Delta,
		Reason: req.Reason,
	}
}

func InventoryEntitiesToModels(entities []*entities.Inventory) []*models.Inventory {
	if entities == nil {
		return nil
	}

	models := make([]*models.Inventory, len(entities))
	for i, entity := range entities {
		models[i] = InventoryEntityToModel(entity)
	}
	return models
}

func InventoryEntitiesToResponses(entities []*entities.Inventory) []*models.InventoryResponse {
	if entities == nil {
		return nil
	}

	responses := make([]*models.InventoryResponse, len(entities))
	for i, entity := range entities {
		responses[i] = InventoryEntityToResponse(entity)
	}
	return responses
}
