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

// GetByID retrieves a tenant by ID
func (r *repository) GetByID(ctx context.Context, id string) (*domaintenant.Tenant, error) {
	var tenantByID models.TenantByID

	query := `SELECT id, name, slug, status, created_at, updated_at,
	          created_from_ip_address, created_from_ip_timestamp, modified_from_ip_address, modified_from_ip_timestamp
	          FROM tenants_by_id
	          WHERE id = ?`

	err := r.session.Query(query, id).
		Consistency(gocql.Quorum).
		Scan(&tenantByID.ID, &tenantByID.Name, &tenantByID.Slug, &tenantByID.Status,
			&tenantByID.CreatedAt, &tenantByID.UpdatedAt,
			&tenantByID.CreatedFromIPAddress, &tenantByID.CreatedFromIPTimestamp,
			&tenantByID.ModifiedFromIPAddress, &tenantByID.ModifiedFromIPTimestamp)

	if err != nil {
		if err == gocql.ErrNotFound {
			return nil, domaintenant.ErrTenantNotFound
		}
		return nil, err
	}

	return tenantByID.ToTenant(), nil
}

// GetBySlug retrieves a tenant by slug
func (r *repository) GetBySlug(ctx context.Context, slug string) (*domaintenant.Tenant, error) {
	var tenantBySlug models.TenantBySlug

	query := `SELECT slug, id, name, status, created_at, updated_at,
	          created_from_ip_address, created_from_ip_timestamp, modified_from_ip_address, modified_from_ip_timestamp
	          FROM tenants_by_slug
	          WHERE slug = ?`

	err := r.session.Query(query, slug).
		Consistency(gocql.Quorum).
		Scan(&tenantBySlug.Slug, &tenantBySlug.ID, &tenantBySlug.Name, &tenantBySlug.Status,
			&tenantBySlug.CreatedAt, &tenantBySlug.UpdatedAt,
			&tenantBySlug.CreatedFromIPAddress, &tenantBySlug.CreatedFromIPTimestamp,
			&tenantBySlug.ModifiedFromIPAddress, &tenantBySlug.ModifiedFromIPTimestamp)

	if err != nil {
		if err == gocql.ErrNotFound {
			return nil, domaintenant.ErrTenantNotFound
		}
		return nil, err
	}

	return tenantBySlug.ToTenant(), nil
}
