package repository

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	libmongo "haixun-backend/internal/library/mongo"
	"haixun-backend/internal/model/outreach_draft/domain/entity"
	domrepo "haixun-backend/internal/model/outreach_draft/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: "brand_id", Value: 1},
				{Key: "scan_post_id", Value: 1},
				{Key: "create_at", Value: -1},
			},
		},
		{
			Keys: bson.D{
				{Key: "tenant_id", Value: 1},
				{Key: "owner_uid", Value: 1},
				{Key: "persona_id", Value: 1},
				{Key: "scan_post_id", Value: 1},
				{Key: "create_at", Value: -1},
			},
		},
	})
	return err
}

func brandOwnerFilter(tenantID, ownerUID, brandID string) bson.M {
	filter := bson.M{
		"tenant_id": tenantID,
		"owner_uid": ownerUID,
	}
	for k, v := range libmongo.BrandScopeFilter(brandID) {
		filter[k] = v
	}
	return filter
}

func (r *mongoRepository) Create(ctx context.Context, draft *entity.OutreachDraft) error {
	if r.collection == nil {
		return app.For(code.Brand).DBUnavailable("Mongo is not configured")
	}
	if draft == nil {
		return app.For(code.Brand).InputMissingRequired("draft is required")
	}
	_, err := r.collection.InsertOne(ctx, draft)
	return err
}

func draftScopeFilter(tenantID, ownerUID, brandID, topicID string) bson.M {
	filter := brandOwnerFilter(tenantID, ownerUID, brandID)
	topicID = strings.TrimSpace(topicID)
	if topicID != "" {
		filter["topic_id"] = topicID
	}
	return filter
}

func (r *mongoRepository) GetLatestByScanPost(
	ctx context.Context,
	tenantID, ownerUID, brandID, topicID, scanPostID string,
) (*entity.OutreachDraft, error) {
	if r.collection == nil {
		return nil, app.For(code.Brand).DBUnavailable("Mongo is not configured")
	}
	filter := draftScopeFilter(tenantID, ownerUID, brandID, topicID)
	filter["scan_post_id"] = strings.TrimSpace(scanPostID)
	opts := options.FindOne().SetSort(bson.D{{Key: "create_at", Value: -1}})
	var out entity.OutreachDraft
	err := r.collection.FindOne(ctx, filter, opts).Decode(&out)
	if err == mongo.ErrNoDocuments {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &out, nil
}
