package repository

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/publish_inventory/domain/entity"
	domrepo "haixun-backend/internal/model/publish_inventory/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}}, Options: options.Index().SetUnique(true)},
		{Keys: bson.D{{Key: "enabled", Value: 1}}},
	})
	return err
}

func (r *mongoRepository) Get(ctx context.Context, tenantID, ownerUID, accountID string) (*entity.Policy, error) {
	if r.collection == nil {
		return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
	}
	var out entity.Policy
	err := r.collection.FindOne(ctx, actorFilter(tenantID, ownerUID, accountID)).Decode(&out)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, app.For(code.ThreadsAccount).ResNotFound("publish inventory policy not found")
		}
		return nil, err
	}
	return &out, nil
}

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

func (r *mongoRepository) ListEnabled(ctx context.Context, limit int) ([]entity.Policy, error) {
	if r.collection == nil {
		return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
	}
	if limit <= 0 {
		limit = 100
	}
	cur, err := r.collection.Find(ctx, bson.M{"enabled": true}, options.Find().SetLimit(int64(limit)))
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)
	var out []entity.Policy
	if err := cur.All(ctx, &out); err != nil {
		return nil, err
	}
	return out, nil
}

func (r *mongoRepository) DeleteByAccount(ctx context.Context, tenantID, ownerUID, accountID string) error {
	if r.collection == nil {
		return app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
	}
	_, err := r.collection.DeleteOne(ctx, actorFilter(tenantID, ownerUID, accountID))
	return err
}

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