package refreshtokensdb

import (
	"github.com/tech/sendico/pkg/db/repository"
	ri "github.com/tech/sendico/pkg/db/repository/index"
	"github.com/tech/sendico/pkg/db/template"
	"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 RefreshTokenDB struct {
	template.DBImp[*model.RefreshToken]
	clients repository.Repository
}

func Create(logger mlogger.Logger, db *mongo.Database) (*RefreshTokenDB, error) {
	p := &RefreshTokenDB{
		DBImp:   *template.Create[*model.RefreshToken](logger, mservice.RefreshTokens, db),
		clients: repository.CreateMongoRepository(db, mservice.Clients),
	}

	if err := p.Repository.CreateIndex(&ri.Definition{
		Keys:   []ri.Key{{Field: "token", Sort: ri.Asc}},
		Unique: true,
	}); err != nil {
		p.Logger.Error("Failed to create unique token index", zap.Error(err))
		return nil, err
	}

	// Add unique constraint on account/client/device combination
	if err := p.Repository.CreateIndex(&ri.Definition{
		Keys: []ri.Key{
			{Field: "accountRef", Sort: ri.Asc},
			{Field: "clientId", Sort: ri.Asc},
			{Field: "deviceId", Sort: ri.Asc},
		},
		Unique:        true,
		Name:          "unique_active_session",
		PartialFilter: repository.Filter(IsRevokedField, false),
	}); err != nil {
		p.Logger.Error("Failed to create unique account/client/device index", zap.Error(err))
		return nil, err
	}

	if err := p.Repository.CreateIndex(&ri.Definition{
		Keys: []ri.Key{{Field: IsRevokedField, Sort: ri.Asc}},
	}); err != nil {
		p.Logger.Error("Failed to create unique token revokation status index", zap.Error(err))
		return nil, err
	}

	if err := p.clients.CreateIndex(&ri.Definition{
		Keys:   []ri.Key{{Field: "clientId", Sort: ri.Asc}},
		Unique: true,
	}); err != nil {
		p.Logger.Error("Failed to create unique client identifier index", zap.Error(err))
		return nil, err
	}

	return p, nil
}
