package invitationdb

import (
	"context"

	"github.com/tech/sendico/pkg/auth"
	"github.com/tech/sendico/pkg/db/policy"
	"github.com/tech/sendico/pkg/db/repository"
	ri "github.com/tech/sendico/pkg/db/repository/index"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.uber.org/zap"
)

type InvitationDB struct {
	auth.ProtectedDBImp[*model.Invitation]
}

func Create(
	ctx context.Context,
	logger mlogger.Logger,
	enforcer auth.Enforcer,
	pdb policy.DB,
	db *mongo.Database,
) (*InvitationDB, error) {
	p, err := auth.CreateDBImp[*model.Invitation](ctx, logger, pdb, enforcer, mservice.Invitations, db)
	if err != nil {
		return nil, err
	}

	// unique email per organization
	if err := p.DBImp.Repository.CreateIndex(&ri.Definition{
		Keys:   []ri.Key{{Field: repository.OrgField().Build(), Sort: ri.Asc}, {Field: "description.email", Sort: ri.Asc}},
		Unique: true,
	}); err != nil {
		p.DBImp.Logger.Error("Failed to create unique mnemonic index", zap.Error(err))
		return nil, err
	}

	// ttl index
	ttl := int32(0) // zero ttl means expiration on date preset when inserting data
	if err := p.DBImp.Repository.CreateIndex(&ri.Definition{
		Keys: []ri.Key{{Field: "expiresAt", Sort: ri.Asc}},
		TTL:  &ttl,
	}); err != nil {
		p.DBImp.Logger.Warn("Failed to create ttl index in the invitations", zap.Error(err))
		return nil, err
	}

	return &InvitationDB{ProtectedDBImp: *p}, nil
}
