package repository

import (
	"context"
	"strings"

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

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

type mongoRepository struct {
	collection *mongo.Collection
}

func NewMongoRepository(db *mongo.Database) domrepo.Repository {
	if db == nil {
		return &mongoRepository{}
	}
	return &mongoRepository{collection: db.Collection(entity.CollectionName)}
}

func (r *mongoRepository) EnsureIndexes(ctx context.Context) error {
	if r.collection == nil {
		return nil
	}
	_, err := r.collection.Indexes().CreateMany(ctx, []mongo.IndexModel{
		{
			Keys: bson.D{
				{Key: "tenant_id", Value: 1},
				{Key: "owner_uid", Value: 1},
				{Key: "account_id", Value: 1},
				{Key: "media_id", Value: 1},
			},
			Options: options.Index().SetUnique(true),
		},
		{
			Keys: bson.D{
				{Key: "tenant_id", Value: 1},
				{Key: "owner_uid", Value: 1},
				{Key: "account_id", Value: 1},
				{Key: "update_at", Value: -1},
			},
		},
	})
	return err
}

func (r *mongoRepository) Upsert(ctx context.Context, review *entity.Review) (*entity.Review, error) {
	if r.collection == nil {
		return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
	}
	if review == nil {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("review is required")
	}
	filter := actorMediaFilter(review.TenantID, review.OwnerUID, review.AccountID, review.MediaID)
	opts := options.Replace().SetUpsert(true)
	if _, err := r.collection.ReplaceOne(ctx, filter, review, opts); err != nil {
		return nil, err
	}
	return review, nil
}

func (r *mongoRepository) Get(ctx context.Context, tenantID, ownerUID, accountID, mediaID string) (*entity.Review, error) {
	if r.collection == nil {
		return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
	}
	var out entity.Review
	err := r.collection.FindOne(ctx, actorMediaFilter(tenantID, ownerUID, accountID, mediaID)).Decode(&out)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, app.For(code.ThreadsAccount).ResNotFound("own post formula review not found")
		}
		return nil, err
	}
	return &out, nil
}

func (r *mongoRepository) ListByAccount(ctx context.Context, tenantID, ownerUID, accountID string) ([]entity.Review, error) {
	if r.collection == nil {
		return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
	}
	cur, err := r.collection.Find(
		ctx,
		bson.M{
			"tenant_id":  strings.TrimSpace(tenantID),
			"owner_uid":  strings.TrimSpace(ownerUID),
			"account_id": strings.TrimSpace(accountID),
		},
		options.Find().SetSort(bson.D{{Key: "update_at", Value: -1}}),
	)
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)
	var out []entity.Review
	if err := cur.All(ctx, &out); err != nil {
		return nil, err
	}
	return out, nil
}

func actorMediaFilter(tenantID, ownerUID, accountID, mediaID string) bson.M {
	return bson.M{
		"tenant_id":  strings.TrimSpace(tenantID),
		"owner_uid":  strings.TrimSpace(ownerUID),
		"account_id": strings.TrimSpace(accountID),
		"media_id":   strings.TrimSpace(mediaID),
	}
}
