package repository

import (
	"context"

	libmongo "apps/backend/internal/lib/mongo"
	"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"
)

type MonStore struct {
	profiles      *mon.Model
	demandMaps    *mon.Model
	watches       *mon.Model
	opportunities *mon.Model
	reviewEvents  *mon.Model
	sweeps        *mon.Model
	replies       *mon.Model
}

func NewMonStore(uri, database string) *MonStore {
	uri = libmongo.MustMongoURI(uri)
	return &MonStore{
		profiles:      mon.MustNewModel(uri, database, "radar_service_profiles"),
		demandMaps:    mon.MustNewModel(uri, database, "radar_demand_maps"),
		watches:       mon.MustNewModel(uri, database, "radar_watches"),
		opportunities: mon.MustNewModel(uri, database, "radar_opportunities"),
		reviewEvents:  mon.MustNewModel(uri, database, "radar_opportunity_review_events"),
		sweeps:        mon.MustNewModel(uri, database, "radar_sweeps"),
		replies:       mon.MustNewModel(uri, database, "radar_replies"),
	}
}

func (s *MonStore) GetServiceProfile(ctx context.Context, ownerUID int64) (*domain.ServiceProfile, error) {
	var p domain.ServiceProfile
	err := s.profiles.FindOne(ctx, &p, bson.M{"_id": ownerUID})
	if err == mon.ErrNotFound {
		return nil, domain.ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	return &p, nil
}

// SaveServiceProfile 整份覆寫（每會員一份）。created_at 由 usecase 帶進來，
// 這層不做欄位合併，否則「刪掉一個服務項目」會存不下去。
func (s *MonStore) SaveServiceProfile(ctx context.Context, p *domain.ServiceProfile) error {
	_, err := s.profiles.ReplaceOne(ctx, bson.M{"_id": p.OwnerUID}, p, options.Replace().SetUpsert(true))
	return err
}
