package main

import (
	"fmt"
	"log/slog"
	"os"
	"strings"
)

func findAuthPinFilePath(username string) (string, error) {
	slog.Info("getting datapath for", "user", username)
	dataPath, err := getDataPath(fsFriendlyJid(username), true)
	if err != nil {
		return strEmpty, fmt.Errorf("find auth pin file path: %w", err)
	}
	return fmt.Sprintf("%sauthpin", dataPath), nil
}

func parseAuthPinFile(username string) (bool, error) {
	// Find auth pin file.
	authPinFile, err := findAuthPinFilePath(username)
	if err != nil {
		return false, fmt.Errorf("parse auth pin file: %w", err)
	}
	// Read file.
	slog.Info("reading auth pin", "file", authPinFile)
	// #nosec G304 -- auth pin file comes from the local system, it's no untrusted input from the network
	f, err := os.ReadFile(authPinFile)
	if err != nil {
		return false, fmt.Errorf("parse auth pin file: %w", err)
	}
	// Strip trailing newline.
	content := strings.TrimSuffix(string(f), "\n")
	noPLAIN := content == "noPLAIN"
	slog.Info("parsing content", "noPLAIN", noPLAIN)
	return noPLAIN, nil
}

func writeAuthPinFile(username string) error {
	// Find auth pin file.
	authPinFile, err := findAuthPinFilePath(username)
	if err != nil {
		return fmt.Errorf("write auth pin file: %w", err)
	}
	slog.Info("writing auth pin", "file", authPinFile)
	err = os.WriteFile(authPinFile, []byte("noPLAIN\n"), 0o400)
	return err
}
