package transform

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

func CreateAddressRequestDTOToEntity(address *dto.CreateAddressRequest, countryID int64) *entities.Address {
	return &entities.Address{
		Address1:          address.Address1,
		Address2:          address.Address2,
		PostalCode:        address.PostalCode,
		UnitNumber:        address.UnitNumber,
		CountryID:         countryID,
		Deactivate:        false,
		SubLevelLocations: ConvertSubLevelLocationsDTOToEntity(address.SubLevelLocationIDs),
	}
}

func AddressEntityToDTO(address *entities.Address) *dto.Address {
	var locations = make([]*dto.SubLevelLocation, 0)
	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: ConvertSubLevelLocationsDTOToEntity(address.SubLevelLocationIDs),
	}
}

func ConvertSubLevelLocationsDTOToEntity(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,
		},
	}
}
