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"
)

// Create creates a new tenant
// Uses batched writes to maintain consistency across denormalized tables
func (r *repository) Create(ctx context.Context, t *domaintenant.Tenant) error {
	// 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)

	// Insert into tenants_by_id table
	batch.Query(`INSERT INTO tenants_by_id (id, name, slug, status, created_at, updated_at,
	             created_from_ip_address, created_from_ip_timestamp, modified_from_ip_address, modified_from_ip_timestamp)
	             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		tenantByID.ID, tenantByID.Name, tenantByID.Slug, tenantByID.Status,
		tenantByID.CreatedAt, tenantByID.UpdatedAt,
		tenantByID.CreatedFromIPAddress, tenantByID.CreatedFromIPTimestamp,
		tenantByID.ModifiedFromIPAddress, tenantByID.ModifiedFromIPTimestamp)

	// Insert into tenants_by_slug table
	batch.Query(`INSERT INTO tenants_by_slug (slug, id, name, status, created_at, updated_at,
	             created_from_ip_address, created_from_ip_timestamp, modified_from_ip_address, modified_from_ip_timestamp)
	             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		tenantBySlug.Slug, tenantBySlug.ID, tenantBySlug.Name, tenantBySlug.Status,
		tenantBySlug.CreatedAt, tenantBySlug.UpdatedAt,
		tenantBySlug.CreatedFromIPAddress, tenantBySlug.CreatedFromIPTimestamp,
		tenantBySlug.ModifiedFromIPAddress, tenantBySlug.ModifiedFromIPTimestamp)

	// Insert into tenants_by_status table
	batch.Query(`INSERT INTO tenants_by_status (status, id, name, slug, created_at, updated_at,
	             created_from_ip_address, created_from_ip_timestamp, modified_from_ip_address, modified_from_ip_timestamp)
	             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		tenantByStatus.Status, tenantByStatus.ID, tenantByStatus.Name, tenantByStatus.Slug,
		tenantByStatus.CreatedAt, tenantByStatus.UpdatedAt,
		tenantByStatus.CreatedFromIPAddress, tenantByStatus.CreatedFromIPTimestamp,
		tenantByStatus.ModifiedFromIPAddress, tenantByStatus.ModifiedFromIPTimestamp)

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

	return nil
}
