package storage

import (
	"encoding/base64"
	"errors"
	"os"
	"path/filepath"
	"strings"

	"sproutgate-backend/internal/models"
)

func (s *Store) SavePending(record models.PendingUser) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	path := s.pendingFilePath(record.Account)
	return writeJSONFile(path, record)
}

func (s *Store) GetPending(account string) (models.PendingUser, bool, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	path := s.pendingFilePath(account)
	if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
		return models.PendingUser{}, false, nil
	}
	var record models.PendingUser
	if err := readJSONFile(path, &record); err != nil {
		return models.PendingUser{}, false, err
	}
	return record, true, nil
}

func (s *Store) DeletePending(account string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	path := s.pendingFilePath(account)
	if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
		return nil
	}
	return os.Remove(path)
}

func (s *Store) pendingFilePath(account string) string {
	return filepath.Join(s.pendingDir, pendingFileName(account))
}

func pendingFileName(account string) string {
	safe := strings.TrimSpace(account)
	if safe == "" {
		safe = "unknown"
	}
	encoded := base64.RawURLEncoding.EncodeToString([]byte(safe))
	return encoded + ".json"
}
