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 CustomerRelationDTO struct {
	Id            uint                     `json:"id"`
	Name          string                   `json:"name"`
	Type          string                   `json:"type"`
	AccountNumber string                   `json:"account_number"`
	Address       string                   `json:"address,omitempty"`
	Balance       float64                  `json:"balance"`
	Pic           *userDTO.UserRelationDTO `json:"pic,omitempty"`
}

type CustomerListDTO struct {
	Id            uint                    `json:"id"`
	Name          string                  `json:"name"`
	PicId         uint                    `json:"pic_id"`
	Type          string                  `json:"type"`
	Address       string                  `json:"address"`
	Phone         string                  `json:"phone"`
	Email         string                  `json:"email"`
	AccountNumber string                  `json:"account_number"`
	Balance       float64                 `json:"balance"`
	Pic           userDTO.UserRelationDTO `json:"pic"`
	CreatedUser   userDTO.UserRelationDTO `json:"created_user"`
	CreatedAt     time.Time               `json:"created_at"`
	UpdatedAt     time.Time               `json:"updated_at"`
}

type CustomerDetailDTO struct {
	CustomerListDTO
}

// === Mapper Functions ===

func ToCustomerRelationDTO(e entity.Customer) CustomerRelationDTO {
	var pic *userDTO.UserRelationDTO
	if e.Pic.Id != 0 {
		mapped := userDTO.ToUserRelationDTO(e.Pic)
		pic = &mapped
	}

	return CustomerRelationDTO{
		Id:            e.Id,
		Name:          e.Name,
		Type:          e.Type,
		AccountNumber: e.AccountNumber,
		Address:       e.Address,
		Balance:       e.Balance,
		Pic:           pic,
	}
}

func ToCustomerListDTO(e entity.Customer) CustomerListDTO {
	var createdUser userDTO.UserRelationDTO
	if e.CreatedUser.Id != 0 {
		mapped := userDTO.ToUserRelationDTO(e.CreatedUser)
		createdUser = mapped
	}

	var pic userDTO.UserRelationDTO
	if e.Pic.Id != 0 {
		mapped := userDTO.ToUserRelationDTO(e.Pic)
		pic = mapped
	}

	return CustomerListDTO{
		Id:            e.Id,
		Name:          e.Name,
		PicId:         e.PicId,
		Type:          e.Type,
		Address:       e.Address,
		Phone:         e.Phone,
		Email:         e.Email,
		AccountNumber: e.AccountNumber,
		Pic:           pic,
		CreatedAt:     e.CreatedAt,
		UpdatedAt:     e.UpdatedAt,
		CreatedUser:   createdUser,
	}
}

func ToCustomerListDTOs(e []entity.Customer) []CustomerListDTO {
	result := make([]CustomerListDTO, len(e))
	for i, r := range e {
		result[i] = ToCustomerListDTO(r)
	}
	return result
}

func ToCustomerDetailDTO(e entity.Customer) CustomerDetailDTO {
	return CustomerDetailDTO{
		CustomerListDTO: ToCustomerListDTO(e),
	}
}
