package db

import (
	"context"

	"github.com/tech/sendico/pkg/auth/internal/native/nstructures"
	"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"
	mutil "github.com/tech/sendico/pkg/mutil/db"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.uber.org/zap"
)

type RolesDBImp struct {
	template.DBImp[*nstructures.RoleAssignment]
}

func (db *RolesDBImp) Roles(ctx context.Context, accountRef, organizationRef bson.ObjectID) ([]nstructures.RoleAssignment, error) {
	return mutil.GetObjects[nstructures.RoleAssignment](
		ctx,
		db.Logger,
		repository.Query().And(
			repository.Filter("role.accountRef", accountRef),
			repository.Filter("role.organizationRef", organizationRef),
		),
		nil,
		db.Repository,
	)
}

func (db *RolesDBImp) RolesForVenue(ctx context.Context, organizationRef bson.ObjectID) ([]nstructures.RoleAssignment, error) {
	return mutil.GetObjects[nstructures.RoleAssignment](
		ctx,
		db.Logger,
		repository.Query().And(
			repository.Filter("role.organizationRef", organizationRef),
		),
		nil,
		db.Repository,
	)
}

func (db *RolesDBImp) DeleteRole(ctx context.Context, roleRef bson.ObjectID) error {
	return db.DeleteMany(
		ctx,
		repository.Query().And(
			repository.Filter("role.descriptionRef", roleRef),
		),
	)
}

func (db *RolesDBImp) RemoveRole(ctx context.Context, roleRef, organizationRef, accountRef bson.ObjectID) error {
	return db.DeleteMany(
		ctx,
		repository.Query().And(
			repository.Filter("role.accountRef", accountRef),
			repository.Filter("role.organizationRef", organizationRef),
			repository.Filter("role.descriptionRef", roleRef),
		),
	)
}

func NewRolesDB(logger mlogger.Logger, db *mongo.Database) (*RolesDBImp, error) {
	p := &RolesDBImp{
		DBImp: *template.Create[*nstructures.RoleAssignment](logger, "role_assignments", db),
	}

	if err := p.Repository.CreateIndex(&ri.Definition{
		Keys: []ri.Key{{Field: "role.organizationRef", Sort: ri.Asc}},
	}); err != nil {
		p.Logger.Warn("Failed to prepare venue index", zap.Error(err))
		return nil, err
	}

	if err := p.Repository.CreateIndex(&ri.Definition{
		Keys: []ri.Key{{Field: "role.descriptionRef", Sort: ri.Asc}},
	}); err != nil {
		p.Logger.Warn("Failed to prepare role description index", zap.Error(err))
		return nil, err
	}

	uniqueRoleConstaint := &ri.Definition{
		Keys: []ri.Key{
			{Field: "role.organizationRef", Sort: ri.Asc},
			{Field: "role.accountRef", Sort: ri.Asc},
			{Field: "role.descriptionRef", Sort: ri.Asc},
		},
		Unique: true,
	}
	if err := p.Repository.CreateIndex(uniqueRoleConstaint); err != nil {
		p.Logger.Warn("Failed to prepare role assignment index", zap.Error(err))
		return nil, err
	}

	return p, nil
}
