package dto

import (
	"time"

	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)

// === DTO Structs ===

type SupplierRelationDTO struct {
	Id       uint   `json:"id"`
	Name     string `json:"name"`
	Alias    string `json:"alias"`
	Category string `json:"category"`
}

type SupplierListDTO struct {
	SupplierRelationDTO
	Pic           string                   `json:"pic"`
	Type          string                   `json:"type"`
	Hatchery      *string                  `json:"hatchery,omitempty"`
	Phone         string                   `json:"phone"`
	Email         string                   `json:"email"`
	Address       string                   `json:"address"`
	Npwp          *string                  `json:"npwp,omitempty"`
	AccountNumber *string                  `json:"account_number,omitempty"`
	Balance       float64                  `json:"balance"`
	DueDate       int                      `json:"due_date"`
	CreatedUser   *userDTO.UserRelationDTO `json:"created_user"`
	CreatedAt     time.Time                `json:"created_at"`
	UpdatedAt     time.Time                `json:"updated_at"`
}

type SupplierDetailDTO struct {
	SupplierListDTO
	Products  []SupplierProductDTO  `json:"products"`
	Nonstocks []SupplierNonstockDTO `json:"nonstocks"`
}

// === Mapper Functions ===

func ToSupplierRelationDTO(e entity.Supplier) SupplierRelationDTO {
	return SupplierRelationDTO{
		Id:       e.Id,
		Name:     e.Name,
		Alias:    e.Alias,
		Category: e.Category,
	}
}

func ToSupplierListDTO(e entity.Supplier) SupplierListDTO {
	var createdUser *userDTO.UserRelationDTO
	if e.CreatedUser.Id != 0 {
		mapped := userDTO.ToUserRelationDTO(e.CreatedUser)
		createdUser = &mapped
	}

	return SupplierListDTO{
		Pic:                 e.Pic,
		Type:                e.Type,
		Hatchery:            e.Hatchery,
		Phone:               e.Phone,
		Email:               e.Email,
		Address:             e.Address,
		Npwp:                e.Npwp,
		AccountNumber:       e.AccountNumber,
		Balance:             e.Balance,
		DueDate:             e.DueDate,
		SupplierRelationDTO: ToSupplierRelationDTO(e),
		CreatedAt:           e.CreatedAt,
		UpdatedAt:           e.UpdatedAt,
		CreatedUser:         createdUser,
	}
}

func ToSupplierListDTOs(e []entity.Supplier) []SupplierListDTO {
	result := make([]SupplierListDTO, len(e))
	for i, r := range e {
		result[i] = ToSupplierListDTO(r)
	}
	return result
}

func ToSupplierDetailDTO(e entity.Supplier) SupplierDetailDTO {
	return SupplierDetailDTO{
		SupplierListDTO: ToSupplierListDTO(e),
		Products:        toSupplierProductDTOs(e.ProductSuppliers),
		Nonstocks:       toSupplierNonstockDTOs(e.NonstockSuppliers),
	}
}
