package dto

import (
	"time"

	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	supplierDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/dto"
	uomDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/uoms/dto"
	userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)

// === DTO Structs ===

type NonstockBaseDTO struct {
	Id    uint   `json:"id"`
	Name  string `json:"name"`
	UomID uint   `json:"uom_id"`
}

type NonstockListDTO struct {
	NonstockBaseDTO
	Uom         *uomDTO.UomBaseDTO            `json:"uom,omitempty"`
	Suppliers   []supplierDTO.SupplierBaseDTO `json:"suppliers"`
	Flags       []string                      `json:"flags"`
	CreatedUser *userDTO.UserBaseDTO          `json:"created_user"`
	CreatedAt   time.Time                     `json:"created_at"`
	UpdatedAt   time.Time                     `json:"updated_at"`
}

type NonstockDetailDTO struct {
	NonstockListDTO
	Flags []string `json:"flags"`
}

// === Mapper Functions ===

func ToNonstockBaseDTO(e entity.Nonstock) NonstockBaseDTO {
	return NonstockBaseDTO{
		Id:    e.Id,
		Name:  e.Name,
		UomID: e.UomId,
	}
}

func ToNonstockListDTO(e entity.Nonstock) NonstockListDTO {
	var createdUser *userDTO.UserBaseDTO
	if e.CreatedUser.Id != 0 {
		mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
		createdUser = &mapped
	}

	var uomRef *uomDTO.UomBaseDTO
	if e.Uom.Id != 0 {
		mapped := uomDTO.ToUomBaseDTO(e.Uom)
		uomRef = &mapped
	}

	suppliers := make([]supplierDTO.SupplierBaseDTO, len(e.Suppliers))
	for i, s := range e.Suppliers {
		suppliers[i] = supplierDTO.ToSupplierBaseDTO(s)
	}

	flags := make([]string, len(e.Flags))
	for i, f := range e.Flags {
		flags[i] = f.Name
	}

	return NonstockListDTO{
		NonstockBaseDTO: ToNonstockBaseDTO(e),
		CreatedAt:       e.CreatedAt,
		UpdatedAt:       e.UpdatedAt,
		CreatedUser:     createdUser,
		Uom:             uomRef,
		Suppliers:       suppliers,
		Flags:           flags,
	}
}

func ToNonstockListDTOs(e []entity.Nonstock) []NonstockListDTO {
	result := make([]NonstockListDTO, len(e))
	for i, r := range e {
		result[i] = ToNonstockListDTO(r)
	}
	return result
}

func ToNonstockDetailDTO(e entity.Nonstock) NonstockDetailDTO {
	flags := make([]string, len(e.Flags))
	for i, f := range e.Flags {
		flags[i] = f.Name
	}

	return NonstockDetailDTO{
		NonstockListDTO: ToNonstockListDTO(e),
		Flags:           flags,
	}
}
