package main

import (
	"os"
	"path/filepath"
	"strings"
)

// lastUserFilePath returns the path to the file storing the last-logged-in user ID.
// Lives in <UserConfigDir>/matrix_client_pc/last_user.txt.
func lastUserFilePath() string {
	cfg, err := os.UserConfigDir()
	if err != nil {
		cfg = filepath.Join(os.Getenv("HOME"), ".config")
	}
	return filepath.Join(cfg, "matrix_client_pc", "last_user.txt")
}

func readLastUser() string {
	b, err := os.ReadFile(lastUserFilePath())
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(b))
}

func writeLastUser(userID string) error {
	path := lastUserFilePath()
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		return err
	}
	return os.WriteFile(path, []byte(userID), 0o600)
}

func clearLastUser() error {
	path := lastUserFilePath()
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return nil
	}
	return os.Remove(path)
}
