package repository

import (
	"context"

	"haixun-backend/internal/library/clock"
	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/job/domain/entity"
	domrepo "haixun-backend/internal/model/job/domain/repository"

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

type mongoEventRepository struct {
	collection *mongo.Collection
}

func NewMongoEventRepository(db *mongo.Database) domrepo.EventRepository {
	if db == nil {
		return &mongoEventRepository{}
	}
	return &mongoEventRepository{collection: db.Collection(entity.EventCollectionName)}
}

func (r *mongoEventRepository) EnsureIndexes(ctx context.Context) error {
	if r.collection == nil {
		return nil
	}
	_, err := r.collection.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys: bson.D{{Key: "job_id", Value: 1}, {Key: "create_at", Value: -1}},
	})
	return err
}

func (r *mongoEventRepository) Append(ctx context.Context, event *entity.Event) error {
	if r.collection == nil {
		return app.For(code.Job).DBUnavailable("Mongo is not configured")
	}
	if event.CreateAt == 0 {
		event.CreateAt = clock.NowUnixNano()
	}
	_, err := r.collection.InsertOne(ctx, event)
	return err
}

func (r *mongoEventRepository) ListByJobID(ctx context.Context, jobID string, limit int64) ([]*entity.Event, error) {
	if r.collection == nil {
		return nil, app.For(code.Job).DBUnavailable("Mongo is not configured")
	}
	if limit <= 0 {
		limit = 50
	}
	cursor, err := r.collection.Find(
		ctx,
		bson.M{"job_id": jobID},
		options.Find().SetSort(bson.D{{Key: "create_at", Value: -1}}).SetLimit(limit),
	)
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

	var items []*entity.Event
	if err := cursor.All(ctx, &items); err != nil {
		return nil, err
	}
	return items, nil
}
