module Sessions
  class Create
    def initialize(user:, match:, params:)
      @user = user
      @match = match
      @params = params
    end

    def call
      platform = @params[:platform].presence || "matchlivetv"
      ent = @match.team.entitlements
      ent.assert_can_stream_on!(platform)
      ent.assert_concurrent_stream!

      session = StreamSession.new(
        match: @match,
        user: @user,
        platform: platform,
        privacy_status: @params[:privacy_status] || "unlisted",
        quality_preset: @params[:quality_preset] || "720p_30_2.5mbps",
        target_bitrate: @params[:target_bitrate] || 2_500_000,
        target_fps: @params[:target_fps] || 30,
        status: "idle"
      )

      if session.platform == "youtube"
        attach_youtube_broadcast!(session)
      end

      StreamSession.transaction do
        session.save!
        session.create_score_state!
        Mediamtx::Client.new.create_path(session)
        log_event(session, "pairing", { created: true, platform: session.platform })
      end

      session
    end

    private

    def attach_youtube_broadcast!(session)
      yt = Youtube::BroadcastService.new(session.match.team)
      title = "#{session.match.team.name} vs #{session.match.opponent_name}"
      broadcast = yt.create_broadcast!(
        title: title,
        privacy_status: session.privacy_status,
        scheduled_at: session.match.scheduled_at
      )

      session.youtube_broadcast_id = broadcast[:broadcast_id]
      session.youtube_stream_id = broadcast[:stream_id]
      session.stream_key = broadcast[:stream_key]
      session.rtmp_url = broadcast[:rtmp_url]
    end

    def log_event(session, type, metadata)
      session.stream_events.create!(event_type: type, metadata: metadata, occurred_at: Time.current)
    end
  end
end
