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

// ListByStatus retrieves all tenants with the specified status (paginated)
// Uses the tenants_by_status table for efficient filtering
func (r *repository) ListByStatus(ctx context.Context, status domaintenant.Status, limit int) ([]*domaintenant.Tenant, error) {
	query := `SELECT status, id, name, slug, created_at, updated_at,
	          created_from_ip_address, created_from_ip_timestamp, modified_from_ip_address, modified_from_ip_timestamp
	          FROM tenants_by_status
	          WHERE status = ?
	          LIMIT ?`

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

	var tenants []*domaintenant.Tenant
	var tenantByStatus models.TenantByStatus

	for iter.Scan(&tenantByStatus.Status, &tenantByStatus.ID, &tenantByStatus.Name, &tenantByStatus.Slug,
		&tenantByStatus.CreatedAt, &tenantByStatus.UpdatedAt,
		&tenantByStatus.CreatedFromIPAddress, &tenantByStatus.CreatedFromIPTimestamp,
		&tenantByStatus.ModifiedFromIPAddress, &tenantByStatus.ModifiedFromIPTimestamp) {
		tenants = append(tenants, tenantByStatus.ToTenant())
	}

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

	return tenants, nil
}
