package repository

import (
	"context"
	"fmt"

	libmongo "gateway/internal/library/mongo"
)

const bsonOpSet = "$set"

// EnsureMongoIndexes creates indexes for member module collections.
func EnsureMongoIndexes(ctx context.Context, conf *libmongo.Conf) error {
	if conf == nil || conf.Host == "" {
		return nil
	}
	if err := ensureMemberIndexes(ctx, conf); err != nil {
		return err
	}
	if err := ensureTenantIndexes(ctx, conf); err != nil {
		return err
	}
	return ensureIdentityIndexes(ctx, conf)
}

func ensureMemberIndexes(ctx context.Context, conf *libmongo.Conf) error {
	//nolint:contextcheck // repository ctor pings Mongo at startup without caller ctx
	repo, ok := NewMemberRepository(MemberRepositoryParam{Conf: conf}).(*memberRepository)
	if !ok {
		return fmt.Errorf("member: unexpected repository type")
	}
	return repo.Index20260520001UP(ctx)
}

func ensureTenantIndexes(ctx context.Context, conf *libmongo.Conf) error {
	//nolint:contextcheck // repository ctor pings Mongo at startup without caller ctx
	repo, ok := NewTenantRepository(TenantRepositoryParam{Conf: conf}).(*tenantRepository)
	if !ok {
		return fmt.Errorf("member: unexpected tenant repository type")
	}
	return repo.Index20260520001UP(ctx)
}

func ensureIdentityIndexes(ctx context.Context, conf *libmongo.Conf) error {
	//nolint:contextcheck // repository ctor pings Mongo at startup without caller ctx
	repo, ok := NewIdentityRepository(IdentityRepositoryParam{Conf: conf}).(*identityRepository)
	if !ok {
		return fmt.Errorf("member: unexpected identity repository type")
	}
	return repo.Index20260520001UP(ctx)
}
