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"
	userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)

// === DTO Structs ===

type LocationRelationDTO struct {
	Id      uint                     `json:"id"`
	Name    string                   `json:"name"`
	Address string                   `json:"address"`
	Area    *areaDTO.AreaRelationDTO `json:"area,omitempty"`
}

type LocationListDTO struct {
	Id          uint                     `json:"id"`
	Name        string                   `json:"name"`
	Address     string                   `json:"address"`
	Area        *areaDTO.AreaRelationDTO `json:"area"`
	CreatedUser *userDTO.UserRelationDTO `json:"created_user"`
	CreatedAt   time.Time                `json:"created_at"`
	UpdatedAt   time.Time                `json:"updated_at"`
}

type LocationDetailDTO struct {
	LocationListDTO
}

// === Mapper Functions ===

func ToLocationRelationDTO(e entity.Location) LocationRelationDTO {
	var area *areaDTO.AreaRelationDTO
	if e.Area.Id != 0 {
		mapped := areaDTO.ToAreaRelationDTO(e.Area)
		area = &mapped
	}

	return LocationRelationDTO{
		Id:      e.Id,
		Name:    e.Name,
		Address: e.Address,
		Area:    area,
	}
}

func ToLocationListDTO(e entity.Location) LocationListDTO {
	var createdUser *userDTO.UserRelationDTO
	if e.CreatedUser.Id != 0 {
		mapped := userDTO.ToUserRelationDTO(e.CreatedUser)
		createdUser = &mapped
	}

	var area *areaDTO.AreaRelationDTO
	if e.Area.Id != 0 {
		mapped := areaDTO.ToAreaRelationDTO(e.Area)
		area = &mapped
	}

	return LocationListDTO{
		Id:          e.Id,
		Name:        e.Name,
		Address:     e.Address,
		Area:        area,
		CreatedUser: createdUser,
		CreatedAt:   e.CreatedAt,
		UpdatedAt:   e.UpdatedAt,
	}
}

func ToLocationListDTOs(e []entity.Location) []LocationListDTO {
	result := make([]LocationListDTO, len(e))
	for i, r := range e {
		result[i] = ToLocationListDTO(r)
	}
	return result
}

func ToLocationDetailDTO(e entity.Location) LocationDetailDTO {
	return LocationDetailDTO{
		LocationListDTO: ToLocationListDTO(e),
	}
}
