package repository

import (
	"context"
	"errors"
	"time"

	libmongo "gateway/internal/library/mongo"
	member "gateway/internal/model/member/domain"
	"gateway/internal/model/member/domain/entity"
	domrepo "gateway/internal/model/member/domain/repository"

	"go.mongodb.org/mongo-driver/v2/bson"
	mongodriver "go.mongodb.org/mongo-driver/v2/mongo"
)

// TenantRepositoryParam configures the Mongo tenant repository.
type TenantRepositoryParam struct {
	Conf *libmongo.Conf
}

type tenantRepository struct {
	db libmongo.DocumentDBUseCase
}

// NewTenantRepository creates a Mongo-backed TenantRepository.
func NewTenantRepository(param TenantRepositoryParam) domrepo.TenantRepository {
	documentDB, err := libmongo.NewDocumentDB(param.Conf, entity.Tenant{}.CollectionName())
	if err != nil {
		panic(err)
	}
	return &tenantRepository{db: documentDB}
}

func (r *tenantRepository) Insert(ctx context.Context, tenant *entity.Tenant) error {
	now := time.Now().UTC().UnixMilli()
	if tenant.ID.IsZero() {
		tenant.ID = bson.NewObjectID()
	}
	if tenant.CreateAt == 0 {
		tenant.CreateAt = now
	}
	if tenant.UpdateAt == 0 {
		tenant.UpdateAt = now
	}
	_, err := r.db.GetClient().InsertOne(ctx, tenant)
	if err != nil {
		if mongodriver.IsDuplicateKeyError(err) {
			return member.ErrDuplicateTenant
		}
		return err
	}
	return nil
}

func (r *tenantRepository) GetByTenantID(ctx context.Context, tenantID string) (*entity.Tenant, error) {
	return r.findOne(ctx, bson.M{member.BSONFieldTenantID: tenantID})
}

func (r *tenantRepository) GetBySlug(ctx context.Context, slug string) (*entity.Tenant, error) {
	return r.findOne(ctx, bson.M{member.BSONFieldSlug: slug})
}

func (r *tenantRepository) GetByUIDPrefix(ctx context.Context, uidPrefix string) (*entity.Tenant, error) {
	return r.findOne(ctx, bson.M{member.BSONFieldUIDPrefix: uidPrefix})
}

func (r *tenantRepository) findOne(ctx context.Context, filter bson.M) (*entity.Tenant, error) {
	var doc entity.Tenant
	if err := r.db.GetClient().FindOne(ctx, &doc, filter); err != nil {
		if errors.Is(err, mongodriver.ErrNoDocuments) {
			return nil, member.ErrTenantNotFound
		}
		return nil, err
	}
	return &doc, nil
}

// Index20260520001UP ensures tenants collection indexes exist.
func (r *tenantRepository) Index20260520001UP(ctx context.Context) error {
	if err := r.db.PopulateIndex(ctx, member.BSONFieldTenantID, 1, true); err != nil {
		return err
	}
	if err := r.db.PopulateIndex(ctx, member.BSONFieldSlug, 1, true); err != nil {
		return err
	}
	return r.db.PopulateIndex(ctx, member.BSONFieldUIDPrefix, 1, true)
}

var _ domrepo.TenantRepository = (*tenantRepository)(nil)
