package user

import (
	"context"

	"github.com/gocql/gocql"
	"go.uber.org/zap"
)

// Delete deletes a user from all tables using batched writes
func (r *repository) Delete(ctx context.Context, tenantID string, id string) error {
	r.logger.Info("deleting user",
		zap.String("tenant_id", tenantID),
		zap.String("id", id))

	// First, get the user to retrieve email and created_date for deleting from other tables
	user, err := r.GetByID(ctx, tenantID, id)
	if err != nil {
		return err
	}

	createdDate := user.CreatedAt.Format("2006-01-02")

	// Use batched writes to maintain consistency across all tables
	batch := r.session.NewBatch(gocql.LoggedBatch)

	// Delete from users_by_id table
	batch.Query(`DELETE FROM users_by_id WHERE tenant_id = ? AND id = ?`,
		tenantID, id)

	// Delete from users_by_email table
	batch.Query(`DELETE FROM users_by_email WHERE tenant_id = ? AND email = ?`,
		tenantID, user.Email)

	// Delete from users_by_date table
	batch.Query(`DELETE FROM users_by_date WHERE tenant_id = ? AND created_date = ? AND id = ?`,
		tenantID, createdDate, id)

	// Execute batch atomically
	if err := r.session.ExecuteBatch(batch); err != nil {
		r.logger.Error("failed to delete user", zap.Error(err))
		return err
	}

	r.logger.Info("user deleted successfully", zap.String("user_id", id))
	return nil
}
