package repository

import (
	"context"
	"errors"
	"time"

	"gateway/internal/library/mongo"
	"gateway/internal/model/notification"
	domentity "gateway/internal/model/notification/domain/entity"
	domrepo "gateway/internal/model/notification/domain/repository"

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

// NotificationDLQRepositoryParam configures the Mongo DLQ repository.
type NotificationDLQRepositoryParam struct {
	Conf *mongo.Conf
}

type notificationDLQRepository struct {
	db mongo.DocumentDBUseCase
}

// NewNotificationDLQRepository creates a Mongo-backed NotificationDLQRepository.
func NewNotificationDLQRepository(param NotificationDLQRepositoryParam) domrepo.NotificationDLQRepository {
	e := domentity.NotificationDLQ{}
	documentDB, err := mongo.NewDocumentDB(param.Conf, e.CollectionName())
	if err != nil {
		panic(err)
	}
	return &notificationDLQRepository{db: documentDB}
}

func (r *notificationDLQRepository) Insert(ctx context.Context, data *domentity.NotificationDLQ) error {
	now := time.Now().UTC().UnixNano()
	if data.ID.IsZero() {
		data.ID = bson.NewObjectID()
	}
	if data.CreateAt == nil {
		data.CreateAt = &now
	}
	if data.OccurredAt == nil {
		data.OccurredAt = &now
	}

	_, err := r.db.GetClient().InsertOne(ctx, data)
	return err
}

func (r *notificationDLQRepository) FindByID(ctx context.Context, tenantID, id string) (*domentity.NotificationDLQ, error) {
	oid, err := bson.ObjectIDFromHex(id)
	if err != nil {
		return nil, notification.ErrInvalidObjectID
	}
	var doc domentity.NotificationDLQ
	filter := bson.M{notification.BSONFieldID: oid, notification.BSONFieldTenantID: tenantID}
	if err := r.db.GetClient().FindOne(ctx, &doc, filter); err != nil {
		if errors.Is(err, mongodriver.ErrNoDocuments) {
			return nil, notification.ErrNotFound
		}
		return nil, err
	}
	return &doc, nil
}

func (r *notificationDLQRepository) ListByTenant(ctx context.Context, tenantID string, limit int64) ([]*domentity.NotificationDLQ, error) {
	if limit <= 0 {
		limit = 50
	}
	if limit > 200 {
		limit = 200
	}
	filter := bson.M{notification.BSONFieldTenantID: tenantID}
	opts := options.Find().SetSort(bson.M{notification.BSONFieldOccurredAt: -1}).SetLimit(limit)
	var docs []*domentity.NotificationDLQ
	if err := r.db.GetClient().Find(ctx, &docs, filter, opts); err != nil {
		return nil, err
	}
	return docs, nil
}

func (r *notificationDLQRepository) Index20260520001UP(ctx context.Context) error {
	return r.db.PopulateMultiIndex(ctx, []string{
		notification.BSONFieldTenantID, notification.BSONFieldOccurredAt,
	}, []int32{1, -1}, false)
}
