package store

import (
	"context"
	"errors"

	"github.com/tech/sendico/ledger/storage"
	"github.com/tech/sendico/ledger/storage/model"
	"github.com/tech/sendico/pkg/db/repository"
	ri "github.com/tech/sendico/pkg/db/repository/index"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.uber.org/zap"
)

type balancesStore struct {
	logger mlogger.Logger
	repo   repository.Repository
}

func NewBalances(logger mlogger.Logger, db *mongo.Database) (storage.BalancesStore, error) {
	repo := repository.CreateMongoRepository(db, model.AccountBalancesCollection)

	// Create unique index on accountRef (one balance per account)
	uniqueIndex := &ri.Definition{
		Keys: []ri.Key{
			{Field: "accountRef", Sort: ri.Asc},
		},
		Unique: true,
	}
	if err := repo.CreateIndex(uniqueIndex); err != nil {
		logger.Error("Failed to ensure balances unique index", zap.Error(err))
		return nil, err
	}

	childLogger := logger.Named(model.AccountBalancesCollection)
	childLogger.Debug("Balances store initialised", zap.String("collection", model.AccountBalancesCollection))

	return &balancesStore{
		logger: childLogger,
		repo:   repo,
	}, nil
}

func (b *balancesStore) Get(ctx context.Context, accountRef bson.ObjectID) (*model.AccountBalance, error) {
	if accountRef.IsZero() {
		b.logger.Warn("Attempt to get balance with zero account ID")
		return nil, merrors.InvalidArgument("balancesStore: zero account ID")
	}

	query := repository.Filter("accountRef", accountRef)

	result := &model.AccountBalance{}
	if err := b.repo.FindOneByFilter(ctx, query, result); err != nil {
		if errors.Is(err, merrors.ErrNoData) {
			b.logger.Debug("Balance not found", mzap.AccRef(accountRef))
			return nil, storage.ErrBalanceNotFound
		}
		b.logger.Warn("Failed to get balance", zap.Error(err), mzap.AccRef(accountRef))
		return nil, err
	}

	b.logger.Debug("Balance loaded", mzap.AccRef(accountRef),
		zap.String("balance", result.Balance))
	return result, nil
}

func (b *balancesStore) Upsert(ctx context.Context, balance *model.AccountBalance) error {
	if balance == nil {
		b.logger.Warn("Attempt to upsert nil balance")
		return merrors.InvalidArgument("balancesStore: nil balance")
	}
	if balance.AccountRef.IsZero() {
		b.logger.Warn("Attempt to upsert balance with zero account ID")
		return merrors.InvalidArgument("balancesStore: zero account ID")
	}

	existing := &model.AccountBalance{}
	filter := repository.Filter("accountRef", balance.AccountRef)

	if err := b.repo.FindOneByFilter(ctx, filter, existing); err != nil {
		if errors.Is(err, merrors.ErrNoData) {
			b.logger.Debug("Inserting new balance", mzap.ObjRef("account_ref", balance.AccountRef))
			return b.repo.Insert(ctx, balance, filter)
		}
		b.logger.Warn("Failed to fetch balance", zap.Error(err), mzap.ObjRef("account_ref", balance.AccountRef))
		return err
	}

	if existing.GetID() != nil {
		balance.SetID(*existing.GetID())
	}
	b.logger.Debug("Updating balance", mzap.ObjRef("account_ref", balance.AccountRef),
		zap.String("balance", balance.Balance))
	return b.repo.Update(ctx, balance)
}

func (b *balancesStore) IncrementBalance(ctx context.Context, accountRef bson.ObjectID, amount string) error {
	if accountRef.IsZero() {
		b.logger.Warn("Attempt to increment balance with zero account ID")
		return merrors.InvalidArgument("balancesStore: zero account ID")
	}

	// Note: This implementation uses $inc on a string field, which won't work.
	// In a real implementation, you'd need to:
	// 1. Fetch the balance
	// 2. Parse amount strings to decimal
	// 3. Add them
	// 4. Update with optimistic locking via version field
	// For now, return not implemented to indicate this needs proper decimal handling
	b.logger.Warn("IncrementBalance not fully implemented - requires decimal arithmetic")
	return merrors.NotImplemented("IncrementBalance requires proper decimal handling")
}
