package repository

import (
	"context"

	"apps/backend/internal/module/radar/domain"

	"github.com/zeromicro/go-zero/core/stores/mon"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func (s *MonStore) SaveReply(ctx context.Context, r *domain.ReplyVariant) error {
	_, err := s.replies.ReplaceOne(ctx, bson.M{"_id": r.ID}, r, options.Replace().SetUpsert(true))
	return err
}

func (s *MonStore) ListReplies(ctx context.Context, ownerUID int64, opportunityID string) ([]*domain.ReplyVariant, error) {
	var list []*domain.ReplyVariant
	err := s.replies.Find(ctx, &list, bson.M{
		"owner_uid":      ownerUID,
		"opportunity_id": opportunityID,
	}, options.Find().SetSort(bson.D{{Key: "created_at", Value: -1}}))
	return list, err
}

func (s *MonStore) ListRepliesForOpportunities(ctx context.Context, ownerUID int64, opportunityIDs []string) (map[string][]*domain.ReplyVariant, error) {
	out := make(map[string][]*domain.ReplyVariant, len(opportunityIDs))
	if len(opportunityIDs) == 0 {
		return out, nil
	}
	var list []*domain.ReplyVariant
	err := s.replies.Find(ctx, &list, bson.M{
		"owner_uid":      ownerUID,
		"opportunity_id": bson.M{"$in": opportunityIDs},
	}, options.Find().SetSort(bson.D{{Key: "created_at", Value: -1}}))
	if err != nil {
		return nil, err
	}
	for _, r := range list {
		out[r.OpportunityID] = append(out[r.OpportunityID], r)
	}
	return out, nil
}

func (s *MonStore) GetReply(ctx context.Context, id string) (*domain.ReplyVariant, error) {
	var r domain.ReplyVariant
	err := s.replies.FindOne(ctx, &r, bson.M{"_id": id})
	if err == mon.ErrNotFound {
		return nil, domain.ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	return &r, nil
}
