package telegram

import (
	
	
	

	
	

	

	
	
	
)

// AuthLostError is returned by Client.Run when the authorization of a client
// is lost (e.g. the session was terminated from another device) and
// Options.OnAuthLost returned an error.
//
// Use errors.As to match it.
type AuthLostError struct {
	// Err is the RPC error that revealed the lost authorization, e.g.
	// AUTH_KEY_UNREGISTERED or SESSION_REVOKED.
	Err error
	// Reason is the error returned by Options.OnAuthLost.
	Reason error
}

// Error implements error.
func ( *AuthLostError) () string {
	return "authorization lost: " + .Err.Error()
}

// Unwrap returns both underlying errors.
func ( *AuthLostError) () []error {
	if .Reason == nil || .Reason == .Err {
		return []error{.Err}
	}
	return []error{.Err, .Reason}
}

// IsAuthLost reports whether err means that the authorization of the session
// is lost: the auth key is unregistered, the session is revoked or expired,
// the user is deactivated, or the key is used by another connection
// (AUTH_KEY_DUPLICATED).
//
// SESSION_PASSWORD_NEEDED and other "not authorized yet" errors are not
// included.
//
// Errors made from AUTH_KEY_DROP_* service notifications (see
// AuthKeyDropError) are included.
func ( error) bool {
	if tgerr.Is(,
		"AUTH_KEY_UNREGISTERED",
		"AUTH_KEY_INVALID",
		"SESSION_REVOKED",
		"SESSION_EXPIRED",
		"USER_DEACTIVATED",
		"USER_DEACTIVATED_BAN",
		"AUTH_KEY_DUPLICATED",
	) {
		return true
	}
	,  := tgerr.As()
	return  && strings.HasPrefix(.Type, authKeyDropPrefix)
}

// authState tracks whether the client is authorized in current Run.
type authState struct {
	authorized atomic.Bool
	// loggedOut is set by LogOut until the client is authorized again: lost
	// authorization is not reported and the session is not saved.
	loggedOut atomic.Bool
	reported  atomic.Bool
	// stopped is set when OnAuthLost stopped Run.
	stopped atomic.Bool
	// done is closed when the last OnAuthLost call returns, nil if there
	// was none. Calls are chained, so it is closed after all of them.
	done atomic.Pointer[chan struct{}]
}

// waitAuthLost waits for the running OnAuthLost call, if any.
func ( *Client) ( context.Context) error {
	 := .auth.done.Load()
	if  == nil {
		return nil
	}
	select {
	case <-*:
		return nil
	case <-.Done():
		return .Err()
	}
}

// queryWrapper is a request wrapping another one, e.g. invokeWithLayer or
// invokeWithoutUpdates.
type queryWrapper interface {
	GetQuery() bin.Object
}

// unwrapQuery returns the innermost request of invokeWith* and
// initConnection wrappers.
func ( bin.Encoder) bin.Encoder {
	for  := 0;  < 8; ++ {
		,  := .(queryWrapper)
		if ! {
			return 
		}
		 := .GetQuery()
		if  == nil {
			return 
		}
		 = 
	}
	return 
}

// authEffect is how a successful request changes authorization.
type authEffect int

const (
	// authNone means that the request tells nothing about authorization.
	authNone authEffect = iota
	// authAuthorized means that the client is authorized.
	authAuthorized
	// authLoggedOut means that the client logged out.
	authLoggedOut
)

// noAuthRequests are requests outside of auth.*, help.* and langpack.*
// that succeed before sign in is complete (2FA, login email setup).
var noAuthRequests = map[string]struct{}{ // nolint:gochecknoglobals
	"account.getPassword":         {},
	"account.deleteAccount":       {},
	"account.sendVerifyEmailCode": {},
	"account.verifyEmail":         {},
}

// authEffectOf reports how the successful result of input changes
// authorization.
func ( bin.Encoder,  bin.Decoder) authEffect {
	 = unwrapQuery()
	switch .(type) {
	case *tg.AuthLogOutRequest:
		return authLoggedOut
	case *tg.AuthSignInRequest,
		*tg.AuthSignUpRequest,
		*tg.AuthCheckPasswordRequest,
		*tg.AuthImportBotAuthorizationRequest,
		*tg.AuthImportAuthorizationRequest,
		*tg.AuthImportWebTokenAuthorizationRequest,
		*tg.AuthRecoverPasswordRequest,
		*tg.AuthImportLoginTokenRequest,
		*tg.AuthExportLoginTokenRequest:
		if isAuthorization() {
			return authAuthorized
		}
		return authNone
	}
	,  := .(interface{ () string })
	if ! {
		return authNone
	}
	 := .()
	if ,  := noAuthRequests[];  {
		return authNone
	}
	for ,  := range []string{"auth.", "help.", "langpack."} {
		if strings.HasPrefix(, ) {
			return authNone
		}
	}
	// Any other successful request requires authorization.
	return authAuthorized
}

// isAuthorization reports whether output is a complete authorization, not
// auth.authorizationSignUpRequired or a login token to wait for.
func ( bin.Decoder) bool {
	switch v := .(type) {
	case *tg.AuthAuthorizationBox:
		,  := .Authorization.(*tg.AuthAuthorization)
		return 
	case *tg.AuthAuthorization:
		return true
	case *tg.AuthLoginTokenBox:
		,  := .LoginToken.(*tg.AuthLoginTokenSuccess)
		if ! {
			return false
		}
		_,  = .Authorization.(*tg.AuthAuthorization)
		return 
	case *tg.AuthLoginTokenSuccess:
		,  := .Authorization.(*tg.AuthAuthorization)
		return 
	default:
		return false
	}
}

// observeAuth tracks authorization by request results and reports lost
// authorization of the primary session.
func ( *Client) ( bin.Encoder,  bin.Decoder,  error) {
	if  == nil {
		switch authEffectOf(, ) {
		case authAuthorized:
			.markAuthorized()
		case authLoggedOut:
			.auth.authorized.Store(false)
		}
		return
	}
	.observeRestriction(, )
	if !IsAuthLost() {
		return
	}
	.authLostDetected()
}

// authLostDetected reports lost authorization revealed by err, if the client
// is authorized.
func ( *Client) ( error) {
	if !.auth.authorized.Load() || .auth.loggedOut.Load() {
		return
	}
	if .ctx != nil && .ctx.Err() != nil {
		// Run is stopping: it no longer waits for reports.
		return
	}
	if !.auth.reported.CompareAndSwap(false, true) {
		return
	}
	.auth.authorized.Store(false)

	// Reported once per authorized -> lost transition, with or without
	// OnAuthLost. The reason is one of IsAuthLost error types.
	 := "unknown"
	if ,  := tgerr.As();  {
		 = .Type
	}
	 := AuthLostKindOf()
	 := context.Background()
	.meters().authLost.Add(, 1, metric.WithAttributes(
		attribute.String("reason", ),
		attribute.String("kind", .String()),
	))
	 := []log.Attr{
		log.String("reason", ),
		log.String("kind", .String()),
		log.Bool("callback", .onAuthLost != nil),
	}
	switch  {
	case AuthLostBanned:
		// Same advice as TDLib gives.
		.log.Error(, "Authorization lost: the account is banned by Telegram. "+
			"If this is a mistake, log in from an official mobile app and follow "+
			"its instructions to recover the account", ...)
	case AuthLostDeleted:
		.log.Error(, "Authorization lost: the account is deleted", ...)
	default:
		.log.Warn(, "Authorization lost", ...)
	}
	if .onAuthLost == nil {
		return
	}

	// Call OnAuthLost on its own goroutine, so that the failing request
	// returns at once and the callback can make requests. Run and the
	// connect-time Self wait for it via done.
	//
	// A report may start while the previous one still runs, if the callback
	// signed in again and authorization was lost again: reports are chained,
	// so they run in order and done of the last one covers all.
	 := make(chan struct{})
	 := .auth.done.Swap(&)
	go func() {
		defer close()
		if  != nil {
			<-*
		}
		.reportAuthLost()
	}()
}

// reportAuthLost calls OnAuthLost and stops Run if it returns an error.
func ( *Client) ( error) {
	// The failing request's context may be about to expire: the callback
	// gets the context of Run, so that it can sign in again.
	 := .ctx
	if  == nil {
		 = context.Background()
	}
	 := .onAuthLost(, )
	if  == nil {
		// Allow reporting again after next authorization.
		.auth.reported.Store(false)
		return
	}
	.auth.stopped.Store(true)
	select {
	case .authLost <- &AuthLostError{Err: , Reason: }:
	default:
	}
}

func ( *Client) () {
	if .auth.authorized.Load() {
		return
	}
	.auth.authorized.Store(true)
	.auth.reported.Store(false)
	.auth.loggedOut.Store(false)
}