package repository

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/copy_draft/domain/entity"
	domrepo "haixun-backend/internal/model/copy_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: "persona_id", Value: 1},
				{Key: "create_at", Value: -1},
			},
		},
	})
	return err
}

func personaFilter(tenantID, ownerUID, personaID string) bson.M {
	return bson.M{
		"tenant_id":  strings.TrimSpace(tenantID),
		"owner_uid":  strings.TrimSpace(ownerUID),
		"persona_id": strings.TrimSpace(personaID),
	}
}

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

func (r *mongoRepository) List(ctx context.Context, tenantID, ownerUID, personaID string, limit int) ([]entity.CopyDraft, error) {
	if r.collection == nil {
		return nil, app.For(code.Persona).DBUnavailable("Mongo is not configured")
	}
	if limit <= 0 {
		limit = 50
	}
	if limit > 200 {
		limit = 200
	}
	opts := options.Find().
		SetSort(bson.D{{Key: "create_at", Value: -1}}).
		SetLimit(int64(limit))
	cur, err := r.collection.Find(ctx, personaFilter(tenantID, ownerUID, personaID), opts)
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)
	var out []entity.CopyDraft
	if err := cur.All(ctx, &out); err != nil {
		return nil, err
	}
	return out, nil
}
