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

// List retrieves all tenants (paginated)
// Note: This is a table scan and should be used sparingly in production
// Consider adding a tenants_by_status table for filtered queries
func (r *repository) List(ctx context.Context, limit int) ([]*domaintenant.Tenant, error) {
	query := `SELECT id, name, slug, status, created_at, updated_at
	          FROM tenants_by_id
	          LIMIT ?`

	iter := r.session.Query(query, limit).
		Consistency(gocql.Quorum).
		Iter()

	var tenants []*domaintenant.Tenant
	var tenantByID models.TenantByID

	for iter.Scan(&tenantByID.ID, &tenantByID.Name, &tenantByID.Slug, &tenantByID.Status,
		&tenantByID.CreatedAt, &tenantByID.UpdatedAt) {
		tenants = append(tenants, tenantByID.ToTenant())
	}

	if err := iter.Close(); err != nil {
		return nil, err
	}

	return tenants, nil
}
