package meet

import (
	"context"
	"strings"
	"time"

	"github.com/google/uuid"

	meetpkg "github.com/ultisuite/ulti-backend/internal/meet"
	"github.com/ultisuite/ulti-backend/internal/orgpolicy"
)

type Service struct {
	cfg    *meetpkg.Config
	policy *orgpolicy.Loader
}

func NewService(cfg *meetpkg.Config, policy *orgpolicy.Loader) *Service {
	return &Service{cfg: cfg, policy: policy}
}

func (s *Service) tokenOpts(ctx context.Context, user *meetpkg.UserInfo) meetpkg.TokenOptions {
	opts := meetpkg.TokenOptions{}
	if s.policy == nil {
		return opts
	}
	p, err := s.policy.MeetPolicy(ctx)
	if err != nil || !p.LiveTranscriptionJWT() {
		return opts
	}
	opts.Transcription = user.IsMod || p.AutoStartTranscription
	return opts
}

func (s *Service) CreateRoom(ctx context.Context, name string, user *meetpkg.UserInfo) (*meetpkg.RoomToken, error) {
	roomID := uuid.New().String()[:8]
	if strings.TrimSpace(name) != "" {
		roomID = strings.TrimSpace(name)
	}
	return s.cfg.GenerateToken(roomID, user, 24*time.Hour, s.tokenOpts(ctx, user))
}

func (s *Service) GetToken(ctx context.Context, roomID string, user *meetpkg.UserInfo) (*meetpkg.RoomToken, error) {
	return s.cfg.GenerateToken(roomID, user, 4*time.Hour, s.tokenOpts(ctx, user))
}
