package storage

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

	"sproutgate-backend/internal/models"
)

func (s *Store) SaveSecondaryVerification(record models.SecondaryEmailVerification) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	path := s.secondaryFilePath(record.Account, record.Email)
	return writeJSONFile(path, record)
}

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

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

func (s *Store) secondaryFilePath(account string, email string) string {
	return filepath.Join(s.secondaryDir, secondaryFileName(account, email))
}

func secondaryFileName(account string, email string) string {
	accountSafe := strings.TrimSpace(account)
	emailSafe := strings.TrimSpace(email)
	if accountSafe == "" {
		accountSafe = "unknown"
	}
	if emailSafe == "" {
		emailSafe = "unknown"
	}
	raw := accountSafe + "::" + emailSafe
	encoded := base64.RawURLEncoding.EncodeToString([]byte(raw))
	return encoded + ".json"
}
