package transform

import (
	"github.com/UpmeshLTD/urus-aio/infrastructure/db/entities"
	"github.com/UpmeshLTD/urus-aio/mdm/server/http/dto"
)

func CreateAddressRequestDTOToEntity(address *dto.CreateAddressRequest) *entities.Address {
	return &entities.Address{
		Address1:          address.Address1,
		Address2:          address.Address2,
		PostalCode:        address.PostalCode,
		UnitNumber:        address.UnitNumber,
		CountryID:         entities.CountryIdsMap[address.CountryCode],
		Deactivate:        false,
		SubLevelLocations: SubLevelLocationsDTOToEntity(address.SubLevelLocationIDs),
	}
}

func AddressEntityToDTO(address *entities.Address) *dto.Address {
	var locations []*dto.SubLevelLocation
	for _, v := range address.SortSubLevelLocations() {
		locations = append(locations, &dto.SubLevelLocation{
			ID:                v.ID.ToInt64(),
			InternationalName: v.InternationalName,
			LocalizedName:     v.LocalizedName,
			ParentID:          v.ParentID,
		})
	}

	return &dto.Address{
		ID:                address.ID.ToInt64(),
		Address1:          address.Address1,
		Address2:          address.Address2,
		PostalCode:        address.PostalCode,
		UnitNumber:        address.UnitNumber,
		CountryID:         address.CountryID,
		Deactivate:        address.Deactivate,
		SubLevelLocations: locations,
	}
}

func UpdateAddressRequestDTOToEntity(address *dto.UpdateAddressRequest) *entities.Address {
	return &entities.Address{
		Address1:          address.Address1,
		Address2:          address.Address2,
		PostalCode:        address.PostalCode,
		UnitNumber:        address.UnitNumber,
		Deactivate:        address.Deactivate,
		SubLevelLocations: SubLevelLocationsDTOToEntity(address.SubLevelLocationIDs),
	}
}

func SubLevelLocationsDTOToEntity(subLevelLocations []int64) []entities.Location {
	var locations []entities.Location
	for _, v := range subLevelLocations {
		locations = append(locations, entities.Location{
			BaseEntity: entities.BaseEntity{
				ID: entities.ID{
					ID: v,
				},
			},
		})
	}
	return locations
}

func GetAddressResponseEntityToDTO(address *entities.Address) *dto.CreateAddressResponse {
	var locations []*dto.SubLevelLocation
	for _, v := range address.SubLevelLocations {
		locations = append(locations, &dto.SubLevelLocation{
			ID:                v.ID.ToInt64(),
			InternationalName: v.InternationalName,
			LocalizedName:     v.LocalizedName,
			ParentID:          v.ParentID,
		})
	}

	return &dto.CreateAddressResponse{
		Data: &dto.Address{
			ID:                address.ID.ToInt64(),
			Address1:          address.Address1,
			Address2:          address.Address2,
			PostalCode:        address.PostalCode,
			CountryID:         address.CountryID,
			UnitNumber:        address.UnitNumber,
			Deactivate:        address.Deactivate,
			SubLevelLocations: locations,
		},
	}
}
