package app

import (
	"fmt"

	"code.tnxs.net/taxnexus/lib/api/geo/geo_models"
)

type GeocodeAddressParams struct {
	BusinessAddress *Address
	Account         *Account
	Ref             string
}

func GeocodeAddress(params GeocodeAddressParams, principal *User) (*geo_models.CoordinateBasic, error) {
	if params.BusinessAddress == nil {
		sugar.Infof("ops.geocodeAddress: ❗ Business Address is null, ref = %s", params.Ref)
		deliveryAddress, acctErr := GetDefaultDeliveryAddress(params.Account, principal)
		if acctErr != nil {
			return nil, fmt.Errorf("ops.geocodeAddress: 💣 ⛔ can't determine default delivery address: %w", acctErr)
		}
		params.BusinessAddress = deliveryAddress
	}
	if params.BusinessAddress.City == "" {
		sugar.Infof("ops.geocodeAddress: ❗ Business Address is blank, ref = %s", params.Ref)
		deliveryAddress, acctErr := GetDefaultDeliveryAddress(params.Account, principal)
		if acctErr != nil {
			return nil, fmt.Errorf("ops.geocodeAddress: 💣 ⛔ can't determine default delivery address: %w", acctErr)
		}
		params.BusinessAddress = deliveryAddress
	}
	var situsCoordinate *geo_models.CoordinateBasic
	aCoordinate, err := GetCoordinate(params.BusinessAddress, principal)
	if err == nil {
		situsCoordinate = aCoordinate
	} else {
		sugar.Infof("ops.geocodeAddress: ❗ can't geocode address: %w", err)
		deliveryAddress, acctErr := GetDefaultDeliveryAddress(params.Account, principal)
		if acctErr != nil {
			return nil, fmt.Errorf("ops.geocodeAddress: 💣 ⛔ can't determine default delivery address: %w", acctErr)
		}
		aCoordinate, coordErr := GetCoordinate(deliveryAddress, principal)
		if coordErr != nil {
			return nil, fmt.Errorf("ops.geocodeAddress: 💣 ⛔ can't determine default delivery coordinates: %w", acctErr)
		}
		sugar.Infof("ops.geocodeAddress: ❗ alternate address used for ref = %s", params.Ref)
		situsCoordinate = aCoordinate
	}
	return situsCoordinate, nil
}
