package user

import (
	"context"

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

	domainuser "codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/domain/user"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/repository/user/models"
)

// Update updates an existing user in all tables using batched writes
func (r *repository) Update(ctx context.Context, tenantID string, u *domainuser.User) error {
	r.logger.Info("updating user",
		zap.String("tenant_id", tenantID),
		zap.String("id", u.ID))

	// Convert domain entity to table models
	userByID := models.FromUser(tenantID, u)
	userByEmail := models.FromUserByEmail(tenantID, u)
	userByDate := models.FromUserByDate(tenantID, u)

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

	// Update users_by_id table
	batch.Query(`UPDATE users_by_id
                 SET name = ?, updated_at = ?
                 WHERE tenant_id = ? AND id = ?`,
		userByID.Name, userByID.UpdatedAt, userByID.TenantID, userByID.ID)

	// Update users_by_email table
	batch.Query(`UPDATE users_by_email
                 SET name = ?, updated_at = ?
                 WHERE tenant_id = ? AND email = ?`,
		userByEmail.Name, userByEmail.UpdatedAt, userByEmail.TenantID, userByEmail.Email)

	// Update users_by_date table
	batch.Query(`UPDATE users_by_date
                 SET name = ?, updated_at = ?
                 WHERE tenant_id = ? AND created_date = ? AND id = ?`,
		userByDate.Name, userByDate.UpdatedAt, userByDate.TenantID, userByDate.CreatedDate, userByDate.ID)

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

	r.logger.Info("user updated successfully", zap.String("user_id", u.ID))
	return nil
}
