package wallet

import (
	"context"
	"errors"

	"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
)

var (
	ErrBalanceInsufficient = errors.New("wallet balance is insufficient")
)

func (s *Service) CreateWallet(ctx context.Context, wallet domain.CreateWallet) (domain.Wallet, error) {
	return s.walletStore.CreateWallet(ctx, wallet)
}

func (s *Service) CreateCustomerWallet(ctx context.Context, customerID int64) (domain.CustomerWallet, error) {

	regularWallet, err := s.CreateWallet(ctx, domain.CreateWallet{
		IsWithdraw: true,
		IsBettable: true,
		UserID:     customerID,
	})

	if err != nil {
		return domain.CustomerWallet{}, err
	}

	staticWallet, err := s.CreateWallet(ctx, domain.CreateWallet{
		IsWithdraw: false,
		IsBettable: true,
		UserID:     customerID,
	})

	if err != nil {
		return domain.CustomerWallet{}, err
	}

	return s.walletStore.CreateCustomerWallet(ctx, domain.CreateCustomerWallet{
		CustomerID:      customerID,
		RegularWalletID: regularWallet.ID,
		StaticWalletID:  staticWallet.ID,
	})
}

func (s *Service) GetWalletByID(ctx context.Context, id int64) (domain.Wallet, error) {
	return s.walletStore.GetWalletByID(ctx, id)
}

func (s *Service) GetAllWallets(ctx context.Context) ([]domain.Wallet, error) {
	return s.walletStore.GetAllWallets(ctx)
}

func (s *Service) GetWalletsByUser(ctx context.Context, id int64) ([]domain.Wallet, error) {
	return s.walletStore.GetWalletsByUser(ctx, id)
}

func (s *Service) GetCustomerWallet(ctx context.Context, customerID int64) (domain.GetCustomerWallet, error) {
	return s.walletStore.GetCustomerWallet(ctx, customerID)
}

func (s *Service) GetAllBranchWallets(ctx context.Context) ([]domain.BranchWallet, error) {
	return s.walletStore.GetAllBranchWallets(ctx)
}

func (s *Service) UpdateBalance(ctx context.Context, id int64, balance domain.Currency) error {
	return s.walletStore.UpdateBalance(ctx, id, balance)
}

func (s *Service) AddToWallet(ctx context.Context, id int64, amount domain.Currency) error {
	wallet, err := s.GetWalletByID(ctx, id)
	if err != nil {
		return err
	}

	return s.walletStore.UpdateBalance(ctx, id, wallet.Balance+amount)
}

func (s *Service) DeductFromWallet(ctx context.Context, id int64, amount domain.Currency) error {
	wallet, err := s.GetWalletByID(ctx, id)
	if err != nil {
		return err
	}

	if wallet.Balance < amount {
		return ErrBalanceInsufficient
	}

	return s.walletStore.UpdateBalance(ctx, id, wallet.Balance-amount)
}

func (s *Service) UpdateWalletActive(ctx context.Context, id int64, isActive bool) error {
	return s.walletStore.UpdateWalletActive(ctx, id, isActive)
}
