package services

import (
	"GoMembership/internal/models"
	"GoMembership/internal/repositories"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"strconv"
	"time"
)

type BankAccountServiceInterface interface {
	RegisterBankAccount(bankAccount *models.BankAccount) (int64, error)
}

type BankAccountService struct {
	Repo repositories.BankAccountRepositoryInterface
}

func (service *BankAccountService) RegisterBankAccount(bankAccount *models.BankAccount) (int64, error) {
	bankAccount.MandateDateSigned = time.Now()
	ref, err := generateSEPAMandateReference(strconv.FormatInt(bankAccount.UserID, 10))
	if err != nil {
		return -1, err
	}
	bankAccount.MandateReference = ref

	return service.Repo.CreateBankAccount(bankAccount)
}

func generateUniqueID(length int) (string, error) {
	bytes := make([]byte, length)
	_, err := rand.Read(bytes)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

func generateSEPAMandateReference(userID string) (string, error) {
	today := time.Now().Format("20060102") // Format YYYYMMDD
	uniqueID, err := generateUniqueID(4)   // 4 Bytes = 8 Hex-Zeichen
	if err != nil {
		return "", err
	}
	mandateReference := fmt.Sprintf("%s-%s-%s", userID, today, uniqueID)
	return mandateReference, nil
}
