package provision

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/google/uuid"
	"github.com/mrhid6/vantage/shared/models"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
)

// ErrNameRejected wraps every reason a name cannot become an instance.
var ErrNameRejected = errors.New("organisation name rejected")

const maxSlugAttempts = 50

// CreateInstance inserts an instance under the first free slug derived from name.
//
// The count-then-insert loop is racy on its own. It is safe only because
// instances.slug carries a unique index: a lost race surfaces as a duplicate-key
// error, which we treat as "that slug is taken" and retry. Do not remove the
// duplicate-key branch, and do not remove the index.
func CreateInstance(ctx context.Context, db *mongo.Database, name string) (*models.Instance, error) {
	base, err := BaseSlug(name)
	if err != nil {
		return nil, fmt.Errorf("%w: %s", ErrNameRejected, err.Error())
	}

	for attempt := 1; attempt <= maxSlugAttempts; attempt++ {
		slug := NextSlug(base, attempt)

		n, err := db.Collection("instances").CountDocuments(ctx, bson.M{"slug": slug})
		if err != nil {
			return nil, err
		}
		if n > 0 {
			continue
		}

		inst := models.Instance{
			InstanceID: uuid.NewString(),
			Name:       name,
			Slug:       slug,
			CreatedAt:  time.Now().UTC(),
		}
		if _, err := db.Collection("instances").InsertOne(ctx, inst); err != nil {
			if mongo.IsDuplicateKeyError(err) {
				continue // lost the race; try the next slug
			}
			return nil, err
		}
		return &inst, nil
	}
	return nil, fmt.Errorf("%w: could not find a free slug for %q", ErrNameRejected, name)
}

// RollbackInstance deletes an instance that has no users.
//
// It refuses an instance that has users. Rollback exists to clean up a
// half-finished signup, and an instance with users is not half-finished.
func RollbackInstance(ctx context.Context, db *mongo.Database, instanceID string) error {
	n, err := db.Collection("users").CountDocuments(ctx, bson.M{"instance_id": instanceID})
	if err != nil {
		return err
	}
	if n > 0 {
		return fmt.Errorf("refusing to roll back instance %s: it has %d user(s)", instanceID, n)
	}
	_, err = db.Collection("instances").DeleteOne(ctx, bson.M{"instance_id": instanceID})
	return err
}
