package repository

import (
	"context"
	"sort"

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

func (m *Memory) SaveReply(_ context.Context, r *domain.ReplyVariant) error {
	if r == nil {
		return domain.ErrValidation
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	cp := *r
	m.replies[r.ID] = &cp
	return nil
}

func (m *Memory) ListReplies(_ context.Context, ownerUID int64, opportunityID string) ([]*domain.ReplyVariant, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	out := make([]*domain.ReplyVariant, 0)
	for _, r := range m.replies {
		if r.OwnerUID == ownerUID && r.OpportunityID == opportunityID {
			cp := *r
			out = append(out, &cp)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt > out[j].CreatedAt })
	return out, nil
}

func (m *Memory) ListRepliesForOpportunities(_ 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
	}
	wanted := make(map[string]bool, len(opportunityIDs))
	for _, id := range opportunityIDs {
		wanted[id] = true
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	for _, r := range m.replies {
		if r.OwnerUID != ownerUID || !wanted[r.OpportunityID] {
			continue
		}
		cp := *r
		out[r.OpportunityID] = append(out[r.OpportunityID], &cp)
	}
	for _, group := range out {
		sort.Slice(group, func(i, j int) bool { return group[i].CreatedAt > group[j].CreatedAt })
	}
	return out, nil
}

func (m *Memory) GetReply(_ context.Context, id string) (*domain.ReplyVariant, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	r, ok := m.replies[id]
	if !ok {
		return nil, domain.ErrNotFound
	}
	cp := *r
	return &cp, nil
}
