package repository

import (
	"context"
	"fmt"
	"sync"

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

// Memory 是測試用實作，行為必須與 MonStore 一致（含 ErrNotFound 語意）。
type Memory struct {
	mu            sync.Mutex
	profiles      map[int64]*domain.ServiceProfile
	demandMaps    map[string]*domain.DemandMap
	watches       map[string]*domain.RadarWatch
	opportunities map[string]*domain.Opportunity
	// ownerExternal indexes "ownerUID\0externalID" → opportunity id for O(1) upsert.
	ownerExternal map[string]string
	sweeps        map[string]*domain.RadarSweep
	// jobToSweep indexes job_id → sweep id.
	jobToSweep   map[string]string
	replies      map[string]*domain.ReplyVariant
	reviewEvents map[string][]domain.ReviewEvent
}

func NewMemory() *Memory {
	return &Memory{
		profiles:      map[int64]*domain.ServiceProfile{},
		demandMaps:    map[string]*domain.DemandMap{},
		watches:       map[string]*domain.RadarWatch{},
		opportunities: map[string]*domain.Opportunity{},
		ownerExternal: map[string]string{},
		sweeps:        map[string]*domain.RadarSweep{},
		jobToSweep:    map[string]string{},
		replies:       map[string]*domain.ReplyVariant{},
		reviewEvents:  map[string][]domain.ReviewEvent{},
	}
}

func ownerExternalKey(ownerUID int64, externalID string) string {
	return fmt.Sprintf("%d\x00%s", ownerUID, externalID)
}

func (m *Memory) GetServiceProfile(_ context.Context, ownerUID int64) (*domain.ServiceProfile, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	p, ok := m.profiles[ownerUID]
	if !ok {
		return nil, domain.ErrNotFound
	}
	cp := *p
	return &cp, nil
}

func (m *Memory) SaveServiceProfile(_ context.Context, p *domain.ServiceProfile) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	cp := *p
	m.profiles[p.OwnerUID] = &cp
	return nil
}
