package dto

import (
	"time"

	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	areaDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/areas/dto"
	kandangDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/dto"
	locationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/locations/dto"
	userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)

// === DTO Structs ===

type WarehouseBaseDTO struct {
	Id       uint                         `json:"id"`
	Name     string                       `json:"name"`
	Type     string                       `json:"type"`
	Area     *areaDTO.AreaBaseDTO         `json:"area"`
	Location *locationDTO.LocationBaseDTO `json:"location"`
	Kandang  *kandangDTO.KandangBaseDTO   `json:"kandang"`
}

type WarehouseListDTO struct {
	WarehouseBaseDTO
	CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
	CreatedAt   time.Time            `json:"created_at"`
	UpdatedAt   time.Time            `json:"updated_at"`
}

type WarehouseDetailDTO struct {
	WarehouseListDTO
}

// === Mapper Functions ===

func ToWarehouseBaseDTO(e entity.Warehouse) WarehouseBaseDTO {
	var area *areaDTO.AreaBaseDTO
	if e.Area.Id != 0 {
		mapped := areaDTO.ToAreaBaseDTO(e.Area)
		area = &mapped
	}

	var location *locationDTO.LocationBaseDTO
	if e.Location != nil && e.Location.Id != 0 {
		mapped := locationDTO.ToLocationBaseDTO(*e.Location)
		location = &mapped
	}

	var kandang *kandangDTO.KandangBaseDTO
	if e.Kandang != nil && e.Kandang.Id != 0 {
		mapped := kandangDTO.ToKandangBaseDTO(*e.Kandang)
		kandang = &mapped
	}

	return WarehouseBaseDTO{
		Id:       e.Id,
		Name:     e.Name,
		Type:     e.Type,
		Area:     area,
		Location: location,
		Kandang:  kandang,
	}
}

func ToWarehouseListDTO(e entity.Warehouse) WarehouseListDTO {
	var createdUser *userDTO.UserBaseDTO
	if e.CreatedUser.Id != 0 {
		mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
		createdUser = &mapped
	}

	return WarehouseListDTO{
		WarehouseBaseDTO: ToWarehouseBaseDTO(e),
		CreatedAt:        e.CreatedAt,
		UpdatedAt:        e.UpdatedAt,
		CreatedUser:      createdUser,
	}
}

func ToWarehouseListDTOs(e []entity.Warehouse) []WarehouseListDTO {
	result := make([]WarehouseListDTO, len(e))
	for i, r := range e {
		result[i] = ToWarehouseListDTO(r)
	}
	return result
}

func ToWarehouseDetailDTO(e entity.Warehouse) WarehouseDetailDTO {
	return WarehouseDetailDTO{
		WarehouseListDTO: ToWarehouseListDTO(e),
	}
}
