package tenant

import (
	"context"

	"github.com/gocql/gocql"

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

// Update updates an existing tenant
// Uses batched writes to maintain consistency across denormalized tables
func (r *repository) Update(ctx context.Context, t *domaintenant.Tenant) error {
	// Get the old tenant to check if status changed
	oldTenant, err := r.GetByID(ctx, t.ID)
	if err != nil {
		return err
	}

	// Convert to table models
	tenantByID := models.FromTenant(t)
	tenantBySlug := models.FromTenantBySlug(t)
	tenantByStatus := models.FromTenantByStatus(t)

	// Create batch for atomic write
	batch := r.session.NewBatch(gocql.LoggedBatch)

	// Update tenants_by_id table
	batch.Query(`UPDATE tenants_by_id SET name = ?, slug = ?, status = ?, updated_at = ?
	             WHERE id = ?`,
		tenantByID.Name, tenantByID.Slug, tenantByID.Status, tenantByID.UpdatedAt,
		tenantByID.ID)

	// Update tenants_by_slug table
	// Note: If slug changed, we need to delete old slug entry and insert new one
	// For simplicity, we'll update in place (slug changes require delete + create)
	batch.Query(`UPDATE tenants_by_slug SET id = ?, name = ?, status = ?, updated_at = ?
	             WHERE slug = ?`,
		tenantBySlug.ID, tenantBySlug.Name, tenantBySlug.Status, tenantBySlug.UpdatedAt,
		tenantBySlug.Slug)

	// Handle tenants_by_status table
	// If status changed, delete from old partition and insert into new one
	if oldTenant.Status != t.Status {
		// Delete from old status partition
		batch.Query(`DELETE FROM tenants_by_status WHERE status = ? AND id = ?`,
			string(oldTenant.Status), t.ID)
		// Insert into new status partition
		batch.Query(`INSERT INTO tenants_by_status (status, id, name, slug, created_at, updated_at)
		             VALUES (?, ?, ?, ?, ?, ?)`,
			tenantByStatus.Status, tenantByStatus.ID, tenantByStatus.Name, tenantByStatus.Slug,
			tenantByStatus.CreatedAt, tenantByStatus.UpdatedAt)
	} else {
		// Status didn't change, just update in place
		batch.Query(`UPDATE tenants_by_status SET name = ?, slug = ?, updated_at = ?
		             WHERE status = ? AND id = ?`,
			tenantByStatus.Name, tenantByStatus.Slug, tenantByStatus.UpdatedAt,
			tenantByStatus.Status, tenantByStatus.ID)
	}

	// Execute batch
	if err := r.session.ExecuteBatch(batch); err != nil {
		return err
	}

	return nil
}
