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 mongoTemplateRepository struct {
	collection *mongo.Collection
}

func NewMongoTemplateRepository(db *mongo.Database) domrepo.TemplateRepository {
	if db == nil {
		return &mongoTemplateRepository{}
	}
	return &mongoTemplateRepository{collection: db.Collection(entity.TemplateCollectionName)}
}

func (r *mongoTemplateRepository) EnsureIndexes(ctx context.Context) error {
	if r.collection == nil {
		return nil
	}
	_, err := r.collection.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys:    bson.D{{Key: "type", Value: 1}},
		Options: options.Index().SetUnique(true),
	})
	return err
}

func (r *mongoTemplateRepository) List(ctx context.Context) ([]*entity.Template, error) {
	if r.collection == nil {
		return nil, app.For(code.Job).DBUnavailable("Mongo is not configured")
	}
	cursor, err := r.collection.Find(ctx, bson.M{}, options.Find().SetSort(bson.D{{Key: "type", Value: 1}}))
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

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

func (r *mongoTemplateRepository) FindByType(ctx context.Context, templateType string) (*entity.Template, error) {
	if r.collection == nil {
		return nil, app.For(code.Job).DBUnavailable("Mongo is not configured")
	}
	var item entity.Template
	err := r.collection.FindOne(ctx, bson.M{"type": templateType}).Decode(&item)
	if err == mongo.ErrNoDocuments {
		return nil, app.For(code.Job).ResNotFound("job template not found")
	}
	if err != nil {
		return nil, err
	}
	return &item, nil
}

func (r *mongoTemplateRepository) Upsert(ctx context.Context, template *entity.Template) (*entity.Template, error) {
	if r.collection == nil {
		return nil, app.For(code.Job).DBUnavailable("Mongo is not configured")
	}
	now := clock.NowUnixNano()
	if template.CreateAt == 0 {
		template.CreateAt = now
	}
	template.UpdateAt = now

	filter := bson.M{"type": template.Type}
	update := bson.M{"$set": template}
	opts := options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After)
	var out entity.Template
	err := r.collection.FindOneAndUpdate(ctx, filter, update, opts).Decode(&out)
	if err != nil {
		return nil, err
	}
	return &out, nil
}
