package listing

import (
	"errors"
	"sync"
	"time"

	"gorm.io/gorm"
	"hfb_sys/backend/internal/model"
)

// ListingChatCreator 发布群创建接口(由 chat 模块实现,避免直接依赖)
type ListingChatCreator interface {
	EnsureListingConversation(tx *gorm.DB, listing model.RentalListing, supportAdminID uint64) (conversationID uint64, err error)
}

type Repository struct {
	db                 *gorm.DB
	publicZoneCountsMu sync.Mutex
	publicZoneCounts   publicZoneCountCache
	chatCreator        ListingChatCreator
}

func NewRepository(db *gorm.DB, chatCreator ListingChatCreator) *Repository {
	return &Repository{
		db:          db,
		chatCreator: chatCreator,
	}
}

type publicZoneCountCache struct {
	Counts    map[string]int64
	ExpiresAt time.Time
}

const publicZoneCountCacheTTL = 5 * time.Second

func initialPublishState(reviewRequired bool) (string, string, *time.Time) {
	if reviewRequired {
		return "draft", "pending", nil
	}
	now := time.Now()
	return "published", "approved", &now
}

func IsNotFound(err error) bool {
	return errors.Is(err, gorm.ErrRecordNotFound)
}

// roundMoney 使用统一的角精度（0.1元）
