package recipientdb

import (
	"context"
	"errors"

	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.uber.org/zap"
)

func (db *RecipientDB) SetArchived(ctx context.Context, accountRef, organizationRef, objectRef bson.ObjectID, isArchived, cascade bool) error {
	// Use the ArchivableDB for the main archiving logic
	if err := db.ArchivableDB.SetArchived(ctx, accountRef, objectRef, isArchived); err != nil {
		db.DBImp.Logger.Warn("Failed to change recipient archive status", zap.Error(err),
			mzap.ObjRef("account_ref", accountRef), mzap.ObjRef("organization_ref", organizationRef),
			mzap.ObjRef("recipient_ref", objectRef), zap.Bool("archived", isArchived), zap.Bool("cascade", cascade))
		return err
	}

	if cascade {
		if err := db.setArchivedPaymentMethods(ctx, accountRef, organizationRef, objectRef, isArchived); err != nil {
			db.DBImp.Logger.Warn("Failed to update payment methods archive status", zap.Error(err),
				mzap.ObjRef("account_ref", accountRef), mzap.ObjRef("organization_ref", organizationRef),
				mzap.ObjRef("recipient_ref", objectRef), zap.Bool("archived", isArchived), zap.Bool("cascade", cascade))

			return err
		}
	}

	return nil
}

func (db *RecipientDB) setArchivedPaymentMethods(ctx context.Context, accountRef, organizationRef, recipientRef bson.ObjectID, archived bool) error {
	db.DBImp.Logger.Debug("Setting archived status for recipient payment methods", mzap.ObjRef("recipient_ref", recipientRef), zap.Bool("archived", archived))

	db.DBImp.Logger.Debug("Applying archived status to payment methods for recipient", mzap.ObjRef("recipient_ref", recipientRef))

	// Get all payMethods for the recipient
	payMethods, err := db.pmdb.List(ctx, accountRef, organizationRef, recipientRef, nil)
	if err != nil && !errors.Is(err, merrors.ErrNoData) {
		db.DBImp.Logger.Warn("Failed to fetch payment methods for recipient", zap.Error(err), mzap.ObjRef("recipient_ref", recipientRef))
		return err
	}

	// Archive each payment method
	for _, pmethod := range payMethods {
		if err := db.pmdb.SetArchived(ctx, accountRef, organizationRef, pmethod.ID, archived, true); err != nil {
			db.DBImp.Logger.Warn("Failed to set archived status for payment method", zap.Error(err), mzap.ObjRef("payment_method_ref", pmethod.ID))
			return err
		}
	}

	db.DBImp.Logger.Debug("Successfully updated payment methods archived status", zap.Int("count", len(payMethods)), mzap.ObjRef("recipient_ref", recipientRef))
	return nil
}
