package telegram

import (
	
	

	
	

	
	
	
)

// guestLogOutTimeout bounds auth.logOut on each non-primary DC.
const guestLogOutTimeout = 5 * time.Second

// LogOut logs the client out the way Telegram Desktop and TDLib do:
//
//  1. auth.logOut on the home DC. A 401 error counts as success: the
//     authorization is gone either way.
//  2. auth.logOut on every other DC the client imported the authorization
//     to (pools of *_MIGRATE redirects and of FileDC), best effort; then
//     those pools are closed and their sessions forgotten.
//  3. The stored session is wiped, so the next client started with the same
//     storage creates a new auth key and starts unauthorized.
//
// Like TDLib, LogOut is irrevocable: the local steps run even if auth.logOut
// fails, and its error is returned after them. Lost authorization is not
// reported to OnAuthLost while and after logging out, and the client stops
// saving its session until it is authorized again.
//
// The client keeps running, unauthorized, on its current auth key; sign in
// again or stop it. The auth keys are not destroyed on the server
// (destroy_auth_key).
//
// The result carries auth.loggedOut.future_auth_token, if the server sent
// one: pass it to a later sign-in (auth.sendCode logout_tokens) to skip the
// code.
func ( *Client) ( context.Context) (*tg.AuthLoggedOut, error) {
	.auth.loggedOut.Store(true)

	,  := .API().AuthLogOut()
	if  != nil {
		if ,  := tgerr.As();  && .Code == 401 {
			// Already logged out or the authorization was revoked.
			,  = &tg.AuthLoggedOut{}, nil
		} else {
			 = errors.Wrap(, "auth.logOut")
		}
	}
	.auth.authorized.Store(false)

	.logOutGuests()
	if  := .wipeSession();  != nil &&  == nil {
		 = errors.Wrap(, "wipe session")
	}
	return , 
}

// logOutGuests logs out on every cached non-primary DC pool and closes them.
func ( *Client) ( context.Context) {
	 := 0
	if .session != nil {
		 = .session.Load().DC
	}
	 := map[CloseInvoker]struct{}{}
	for ,  := range []*dcPoolCache{.subConns, .filePools} {
		if  == nil {
			continue
		}
		.mux.Lock()
		 := make(map[int]CloseInvoker, len(.conns))
		for ,  := range .conns {
			[] = 
		}
		.conns = map[int]CloseInvoker{}
		.mux.Unlock()

		for ,  := range  {
			if ,  := [];  {
				continue
			}
			[] = struct{}{}
			if  !=  {
				,  := context.WithTimeout(, guestLogOutTimeout)
				if ,  := tg.NewClient().AuthLogOut();  != nil {
					.log.Debug(, "Guest DC log out failed", log.Int("dc_id", ), log.Error())
				}
				()
			}
			if  := .Close();  != nil {
				.log.Debug(, "Close guest DC pool", log.Int("dc_id", ), log.Error())
			}
		}
	}

	.fileInvokersMux.Lock()
	.fileInvokers = map[int]tg.Invoker{}
	.fileInvokersMux.Unlock()

	.sessionsMux.Lock()
	for  := range .sessions {
		delete(.sessions, )
	}
	for  := range .dcAuthorized {
		delete(.dcAuthorized, )
	}
	for  := range .sessionStates {
		delete(.sessionStates, )
	}
	.sessionsMux.Unlock()
	.selfID.Store(0)
	.selfBot.Store(false)
}

// wipeSession clears the stored session: the session loader treats empty
// data as no session.
func ( *Client) ( context.Context) error {
	,  := .storage.(*session.Loader)
	if ! ||  == nil || .Storage == nil {
		return nil
	}
	return .Storage.StoreSession(, nil)
}