package dto

import "strings"

// DeviceContext is what the app can tell the API about the handset it is
// running on. Register and the two OTP verifications all accept it, so a
// session is identifiable however the customer got in.
//
// Where each field lands, because they do not all live in the same place:
//
//	DeviceToken  users.device_token, users.fcm_token and users.token
//	DeviceType   users.device_type
//	IPAddress    login_histories.ip_address
//	DeviceName   login_histories.device_name
//	Platform     login_histories.platform (and users.device_type when
//	             device_type was not sent separately)
//
// `users` has no ip_address, device_name or platform column — login_histories
// is the table that carries them, one row per session rather than one value
// per account, which is what you want for "where has this account signed in
// from".
type DeviceContext struct {
	DeviceToken string `json:"device_token"`

	// ANDROID, IPHONE or WEB.
	DeviceType string `json:"device_type"`

	DeviceName string `json:"device_name"`

	IPAddress string `json:"ip_address"`

	Platform string `json:"platform"`
}

// HasSession reports whether there is anything worth writing to
// login_histories. A request that carried none of these should not leave an
// empty row behind.
func (d DeviceContext) HasSession() bool {

	return strings.TrimSpace(d.IPAddress) != "" ||
		strings.TrimSpace(d.DeviceName) != "" ||
		strings.TrimSpace(d.Platform) != ""
}

// ResolvedDeviceType is what to store in users.device_type.
//
// Apps send "platform": "Android" and often no device_type at all, so the
// platform stands in for it. Upper-cased because the astrologer side's own
// column is an enum of ANDROID / IPHONE / WEB and the two should agree.
func (d DeviceContext) ResolvedDeviceType() string {

	if value := strings.TrimSpace(d.DeviceType); value != "" {
		return strings.ToUpper(value)
	}

	return strings.ToUpper(strings.TrimSpace(d.Platform))
}
