package storage

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

	"sproutgate-backend/internal/models"
)

func (s *Store) SaveReset(record models.ResetPassword) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	path := s.resetFilePath(record.Account)
	return writeJSONFile(path, record)
}

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

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

func (s *Store) resetFilePath(account string) string {
	return filepath.Join(s.resetDir, resetFileName(account))
}

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