package roomadmin

import (
	"context"
	"fmt"
	"slices"

	"hyapp-admin-server/internal/integration/roomclient"
)

var roomSeatCountCandidates = []int32{10, 15, 20, 25, 30}

type RoomConfig struct {
	CandidateSeatCounts []int32 `json:"candidateSeatCounts"`
	AllowedSeatCounts   []int32 `json:"allowedSeatCounts"`
	DefaultSeatCount    int32   `json:"defaultSeatCount"`
	UpdatedAtMS         int64   `json:"updatedAtMs"`
}

// GetRoomConfig 读取房间座位数配置；缺行时返回产品默认值，不阻塞首次打开配置页。
func (s *Service) GetRoomConfig(ctx context.Context) (RoomConfig, error) {
	if s.roomClient == nil {
		return RoomConfig{}, fmt.Errorf("room service client is not configured")
	}
	config, err := s.roomClient.GetRoomSeatConfig(ctx)
	if err != nil {
		return RoomConfig{}, mapRoomClientError(err)
	}
	return roomConfigFromClient(config)
}

// UpdateRoomConfig 保存后台房间配置；候选集合固定，后台只控制启用项和默认值。
func (s *Service) UpdateRoomConfig(ctx context.Context, req updateRoomConfigRequest) (RoomConfig, error) {
	if s.roomClient == nil {
		return RoomConfig{}, fmt.Errorf("room service client is not configured")
	}
	config, err := normalizeRoomConfig(RoomConfig{
		AllowedSeatCounts: req.AllowedSeatCounts,
		DefaultSeatCount:  req.DefaultSeatCount,
	})
	if err != nil {
		return RoomConfig{}, err
	}
	saved, err := s.roomClient.UpdateRoomSeatConfig(ctx, roomclient.UpdateRoomSeatConfigRequest{
		AllowedSeatCounts: config.AllowedSeatCounts,
		DefaultSeatCount:  config.DefaultSeatCount,
	})
	if err != nil {
		return RoomConfig{}, mapRoomClientError(err)
	}
	return roomConfigFromClient(saved)
}

func defaultRoomConfig() RoomConfig {
	return RoomConfig{
		CandidateSeatCounts: append([]int32(nil), roomSeatCountCandidates...),
		AllowedSeatCounts:   append([]int32(nil), roomSeatCountCandidates...),
		DefaultSeatCount:    15,
	}
}

func normalizeRoomConfig(config RoomConfig) (RoomConfig, error) {
	candidateSet := make(map[int32]bool, len(roomSeatCountCandidates))
	for _, candidate := range roomSeatCountCandidates {
		candidateSet[candidate] = true
	}
	seen := make(map[int32]bool, len(config.AllowedSeatCounts))
	allowed := make([]int32, 0, len(config.AllowedSeatCounts))
	for _, value := range config.AllowedSeatCounts {
		if !candidateSet[value] {
			return RoomConfig{}, fmt.Errorf("%w: 座位数只能选择 10、15、20、25、30", ErrInvalidArgument)
		}
		if seen[value] {
			return RoomConfig{}, fmt.Errorf("%w: 座位数不能重复", ErrInvalidArgument)
		}
		seen[value] = true
		allowed = append(allowed, value)
	}
	if len(allowed) == 0 {
		return RoomConfig{}, fmt.Errorf("%w: 至少启用一个座位数", ErrInvalidArgument)
	}
	slices.Sort(allowed)
	if !seen[config.DefaultSeatCount] {
		return RoomConfig{}, fmt.Errorf("%w: 默认座位数必须在已启用座位数中", ErrInvalidArgument)
	}
	config.CandidateSeatCounts = append([]int32(nil), roomSeatCountCandidates...)
	config.AllowedSeatCounts = allowed
	return config, nil
}

func roomConfigFromClient(input roomclient.RoomSeatConfig) (RoomConfig, error) {
	config := RoomConfig{
		CandidateSeatCounts: input.CandidateSeatCounts,
		AllowedSeatCounts:   input.AllowedSeatCounts,
		DefaultSeatCount:    input.DefaultSeatCount,
		UpdatedAtMS:         input.UpdatedAtMS,
	}
	if len(config.CandidateSeatCounts) == 0 {
		config.CandidateSeatCounts = append([]int32(nil), roomSeatCountCandidates...)
	}
	return normalizeRoomConfig(config)
}
